diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/AddSdkProfileActivity.java b/server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/AddSdkProfileActivity.java index 7d78434848..d55f2de587 100755 --- a/server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/AddSdkProfileActivity.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/AddSdkProfileActivity.java @@ -39,7 +39,8 @@ import java.util.ArrayList; import java.util.List; -public class AddSdkProfileActivity extends AbstractDetailsActivity { +public class AddSdkProfileActivity + extends AbstractDetailsActivity { private String applicationId; @@ -73,16 +74,8 @@ protected SdkProfileDto newEntity() { @Override protected void onEntityRetrieved() { BusyPopup.showPopup(); - KaaAdmin.getDataSource().getSchemaVersionsByApplicationId(applicationId, new AsyncCallback() { - @Override - public void onFailure(Throwable caught) { - BusyPopup.hidePopup(); - Utils.handleException(caught, detailsView); - } - - @Override - public void onSuccess(final SchemaVersions schemaVersions) { - KaaAdmin.getDataSource().getAefMaps(applicationId, new AsyncCallback>() { + KaaAdmin.getDataSource().getSchemaVersionsByApplicationId(applicationId, + new AsyncCallback() { @Override public void onFailure(Throwable caught) { BusyPopup.hidePopup(); @@ -90,9 +83,9 @@ public void onFailure(Throwable caught) { } @Override - public void onSuccess(final List ecfs) { - KaaAdmin.getDataSource().loadUserVerifiers(applicationId, - new AsyncCallback>() { + public void onSuccess(final SchemaVersions schemaVersions) { + KaaAdmin.getDataSource().getAefMaps(applicationId, + new AsyncCallback>() { @Override public void onFailure(Throwable caught) { BusyPopup.hidePopup(); @@ -100,16 +93,27 @@ public void onFailure(Throwable caught) { } @Override - public void onSuccess( - List userVerifiers) { - BusyPopup.hidePopup(); - onInfoRetrieved(schemaVersions, ecfs, userVerifiers); + public void onSuccess(final List ecfs) { + KaaAdmin.getDataSource().loadUserVerifiers(applicationId, + new AsyncCallback>() { + @Override + public void onFailure(Throwable caught) { + BusyPopup.hidePopup(); + Utils.handleException(caught, detailsView); + } + + @Override + public void onSuccess( + List userVerifiers) { + BusyPopup.hidePopup(); + onInfoRetrieved(schemaVersions, ecfs, userVerifiers); + } + } + ); } }); } }); - } - }); } private void onInfoRetrieved(SchemaVersions schemaVersions, @@ -141,14 +145,14 @@ private void onInfoRetrieved(SchemaVersions schemaVersions, protected void onSave() { entity.setName(detailsView.getName().getValue()); - entity.setConfigurationSchemaVersion(detailsView.getConfigurationSchemaVersion(). - getValue().getVersion()); - entity.setProfileSchemaVersion(detailsView.getProfileSchemaVersion(). - getValue().getVersion()); - entity.setNotificationSchemaVersion(detailsView.getNotificationSchemaVersion(). - getValue().getVersion()); - entity.setLogSchemaVersion(detailsView.getLogSchemaVersion(). - getValue().getVersion()); + entity.setConfigurationSchemaVersion(detailsView.getConfigurationSchemaVersion() + .getValue().getVersion()); + entity.setProfileSchemaVersion(detailsView.getProfileSchemaVersion() + .getValue().getVersion()); + entity.setNotificationSchemaVersion(detailsView.getNotificationSchemaVersion() + .getValue().getVersion()); + entity.setLogSchemaVersion(detailsView.getLogSchemaVersion() + .getValue().getVersion()); } @@ -172,13 +176,14 @@ protected void doSave(final EventBus eventBus) { KaaAdmin.getDataSource().validateEcfListInSdkProfile(aefMaps, new AsyncCallback() { + @Override public void onFailure(Throwable caught) { Utils.handleException(caught, detailsView); } @Override - public void onSuccess(Void aVoid) { + public void onSuccess(Void callback) { List aefMapIds = new ArrayList<>(); if (aefMaps != null) { for (AefMapInfoDto aefMap : aefMaps) { @@ -191,24 +196,30 @@ public void onSuccess(Void aVoid) { .getValue().getVerifierToken()); } entity = sdkProfileDto; - if (!sdkProfileDto.getAefMapIds().isEmpty() && sdkProfileDto.getDefaultVerifierToken() == null) { + if (!sdkProfileDto.getAefMapIds().isEmpty() + && sdkProfileDto.getDefaultVerifierToken() == null) { + detailsView.setErrorMessage(Utils.constants.specifyVerifier()); } else { - KaaAdmin.getDataSource().addSdkProfile(sdkProfileDto, new BusyAsyncCallback() { - @Override - public void onSuccessImpl(SdkProfileDto result) { - detailsView.reset(); - AddSdkProfileActivity.this.goTo(new SdkProfilesPlace(applicationId)); - } - - @Override - public void onFailureImpl(Throwable caught) { - Utils.handleException(caught, detailsView); - } - }); + + KaaAdmin.getDataSource().addSdkProfile(sdkProfileDto, + new BusyAsyncCallback() { + @Override + public void onSuccessImpl(SdkProfileDto result) { + detailsView.reset(); + AddSdkProfileActivity.this.goTo(new SdkProfilesPlace(applicationId)); + } + + @Override + public void onFailureImpl(Throwable caught) { + Utils.handleException(caught, detailsView); + } + }); } } + }); + } @Override diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/EndpointProfileActivity.java b/server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/EndpointProfileActivity.java index 0cbc27f946..9bb42a2d0a 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/EndpointProfileActivity.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/admin/client/mvp/activity/EndpointProfileActivity.java @@ -51,7 +51,9 @@ import java.util.ArrayList; import java.util.List; -public class EndpointProfileActivity extends AbstractDetailsActivity { +public class EndpointProfileActivity + extends AbstractDetailsActivity + { public EndpointProfileActivity(EndpointProfilePlace place, ClientFactory clientFactory) { super(place, clientFactory); @@ -65,25 +67,28 @@ public void start(AcceptsOneWidget containerWidget, EventBus eventBus) { protected void bind(final EventBus eventBus) { super.bind(eventBus); - registrations.add(detailsView.getGroupsGrid().addRowActionHandler(new RowActionEventHandler() { - @Override - public void onRowAction(RowActionEvent rowActionEvent) { - String id = rowActionEvent.getClickedId(); - EndpointGroupPlace endpointGroupPlace = new EndpointGroupPlace(place.getApplicationId(), id, false, false); - endpointGroupPlace.setPreviousPlace(place); - goTo(endpointGroupPlace); - } - })); + registrations.add(detailsView.getGroupsGrid().addRowActionHandler( + new RowActionEventHandler() { + @Override + public void onRowAction(RowActionEvent rowActionEvent) { + String id = rowActionEvent.getClickedId(); + EndpointGroupPlace endpointGroupPlace = new EndpointGroupPlace( + place.getApplicationId(), id, false, false); + endpointGroupPlace.setPreviousPlace(place); + goTo(endpointGroupPlace); + } + })); - registrations.add(detailsView.getTopicsGrid().addRowActionHandler(new RowActionEventHandler() { - @Override - public void onRowAction(RowActionEvent rowActionEvent) { - String id = rowActionEvent.getClickedId(); - TopicPlace topicPlace = new TopicPlace(place.getApplicationId(), id); - topicPlace.setPreviousPlace(place); - goTo(topicPlace); - } - })); + registrations.add(detailsView.getTopicsGrid().addRowActionHandler( + new RowActionEventHandler() { + @Override + public void onRowAction(RowActionEvent rowActionEvent) { + String id = rowActionEvent.getClickedId(); + TopicPlace topicPlace = new TopicPlace(place.getApplicationId(), id); + topicPlace.setPreviousPlace(place); + goTo(topicPlace); + } + })); } @Override @@ -121,11 +126,15 @@ protected void onEntityRetrieved() { final SdkProfileDto sdkDto = entity.getSdkProfileDto(); if (sdkDto != null) { String sdkName = sdkDto.getName(); - detailsView.getSdkAnchor().setText((sdkName != null && !sdkName.isEmpty()) ? sdkName : sdkDto.getToken()); + detailsView.getSdkAnchor() + .setText((sdkName != null && !sdkName.isEmpty()) ? sdkName : sdkDto.getToken()); + registrations.add(detailsView.getSdkAnchor().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { - SdkProfilePlace sdkProfilePlace = new SdkProfilePlace(place.getApplicationId(), sdkDto.getId()); + SdkProfilePlace sdkProfilePlace = new SdkProfilePlace(place.getApplicationId(), + sdkDto.getId()); + sdkProfilePlace.setPreviousPlace(place); goTo(sdkProfilePlace); } @@ -160,22 +169,27 @@ public void onClick(ClickEvent clickEvent) { detailsView.getEndpointProfSchemaName().setText(entity.getProfileSchemaName()); - registrations.add(detailsView.getEndpointProfSchemaName().addClickHandler(new ClickHandler() { - @Override - public void onClick(ClickEvent clickEvent) { - ProfileSchemaPlace endpointProfSchemaPlace = new ProfileSchemaPlace(place.getApplicationId(), entity - .getProfileSchemaVersion().getId()); - endpointProfSchemaPlace.setPreviousPlace(place); - goTo(endpointProfSchemaPlace); - } - })); + registrations.add(detailsView.getEndpointProfSchemaName().addClickHandler( + new ClickHandler() { + @Override + public void onClick(ClickEvent clickEvent) { + ProfileSchemaPlace endpointProfSchemaPlace = new ProfileSchemaPlace( + place.getApplicationId(), + entity.getProfileSchemaVersion().getId()); + endpointProfSchemaPlace.setPreviousPlace(place); + goTo(endpointProfSchemaPlace); + } + })); - registrations.add(detailsView.getDownloadEndpointProfileJsonButton().addClickHandler(new ClickHandler() { - @Override - public void onClick(ClickEvent event) { - ServletHelper.downloadEndpointProfile(BaseEncoding.base64().encode(entity.getEndpointKeyHash()), ProfileType.CLIENT); - } - })); + registrations.add(detailsView.getDownloadEndpointProfileJsonButton().addClickHandler( + new ClickHandler() { + @Override + public void onClick(ClickEvent event) { + ServletHelper.downloadEndpointProfile( + BaseEncoding.base64().encode(entity.getEndpointKeyHash()), ProfileType.CLIENT + ); + } + })); detailsView.getEndpointProfForm().setValue(entity.getProfileRecord()); detailsView.getServerProfForm().setValue(entity.getServerProfileRecord()); @@ -185,42 +199,50 @@ public void onClick(ClickEvent event) { registrations.add(detailsView.getServerProfSchemaName().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent clickEvent) { - ServerProfileSchemaPlace serverProfSchemaPlace = new ServerProfileSchemaPlace(place.getApplicationId(), entity - .getServerProfileSchemaVersion().getId()); + ServerProfileSchemaPlace serverProfSchemaPlace = new ServerProfileSchemaPlace( + place.getApplicationId(), entity.getServerProfileSchemaVersion().getId()); serverProfSchemaPlace.setPreviousPlace(place); goTo(serverProfSchemaPlace); } })); - registrations.add(detailsView.getDownloadEndpointConfigurationButton().addClickHandler(new ClickHandler() { - @Override - public void onClick(ClickEvent clickEvent) { - KaaAdmin.getDataSource().findEndpointConfigurationByEndpointKeyHash(BaseEncoding.base64().encode(entity.getEndpointKeyHash()), new BusyAsyncCallback() { + registrations.add(detailsView.getDownloadEndpointConfigurationButton().addClickHandler( + new ClickHandler() { @Override - public void onFailureImpl(Throwable throwable) { - Utils.handleException(throwable, detailsView); + public void onClick(ClickEvent clickEvent) { + KaaAdmin.getDataSource().findEndpointConfigurationByEndpointKeyHash( + BaseEncoding.base64().encode(entity.getEndpointKeyHash()), + new BusyAsyncCallback() { + @Override + public void onFailureImpl(Throwable throwable) { + Utils.handleException(throwable, detailsView); + } + + @Override + public void onSuccessImpl(String str) { + ServletHelper.downloadEndpointConfiguration( + BaseEncoding.base64().encode(entity.getEndpointKeyHash())); + } + } + ); } + })); + registrations.add(detailsView.getDownloadServerProfileJsonButton().addClickHandler( + new ClickHandler() { @Override - public void onSuccessImpl(String s) { - ServletHelper.downloadEndpointConfiguration(BaseEncoding.base64().encode(entity.getEndpointKeyHash())); + public void onClick(ClickEvent event) { + ServletHelper.downloadEndpointProfile( + BaseEncoding.base64().encode(entity.getEndpointKeyHash()), ProfileType.SERVER); } - }); - } - })); - - registrations.add(detailsView.getDownloadServerProfileJsonButton().addClickHandler(new ClickHandler() { - @Override - public void onClick(ClickEvent event) { - ServletHelper.downloadEndpointProfile(BaseEncoding.base64().encode(entity.getEndpointKeyHash()), ProfileType.SERVER); - } - })); + })); registrations.add(detailsView.getEditServerProfileButton().addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { - KaaAdmin.getDataSource().getServerProfileSchemaInfosByEndpointKey(place.getEndpointKeyHash(), + KaaAdmin.getDataSource().getServerProfileSchemaInfosByEndpointKey( + place.getEndpointKeyHash(), new BusyAsyncCallback>() { @Override public void onFailureImpl(Throwable caught) { @@ -229,11 +251,13 @@ public void onFailureImpl(Throwable caught) { @Override public void onSuccessImpl(List result) { - EditSchemaRecordDialog.Listener editSchemaListener = new EditSchemaRecordDialog.Listener() { + EditSchemaRecordDialog.Listener editSchemaListener = + new EditSchemaRecordDialog.Listener() { @Override public void onSave(SchemaInfoDto newValue) { - AsyncCallback callback = new BusyAsyncCallback() { + AsyncCallback callback = + new BusyAsyncCallback() { @Override public void onFailureImpl(Throwable caught) { @@ -246,15 +270,16 @@ public void onSuccessImpl(EndpointProfileDto result) { } }; KaaAdmin.getDataSource().updateServerProfile( - BaseEncoding.base64().encode(entity.getEndpointKeyHash()), newValue.getVersion(), + BaseEncoding.base64().encode(entity.getEndpointKeyHash()), + newValue.getVersion(), newValue.getSchemaForm(), callback); } @Override - public void onCancel() { - } + public void onCancel() {} }; - EditSchemaRecordDialog.showEditSchemaRecordDialog(editSchemaListener, Utils.constants.editServerProfile(), + EditSchemaRecordDialog.showEditSchemaRecordDialog(editSchemaListener, + Utils.constants.editServerProfile(), result, entity.getServerProfileSchemaVersion().getVersion()); } }); @@ -272,6 +297,6 @@ protected void getEntity(String id, final AsyncCallback } @Override - protected void editEntity(EndpointProfileViewDto entity, AsyncCallback callback) { - } + protected void editEntity(EndpointProfileViewDto entity, + AsyncCallback callback) {} } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/admin/servlet/ProfileDownloadServlet.java b/server/node/src/main/java/org/kaaproject/kaa/server/admin/servlet/ProfileDownloadServlet.java index 0263e9d303..5aa6af144b 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/admin/servlet/ProfileDownloadServlet.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/admin/servlet/ProfileDownloadServlet.java @@ -62,20 +62,31 @@ public class ProfileDownloadServlet extends HttpServlet implements Servlet, Serv @Override public void init(ServletConfig config) throws ServletException { super.init(config); - SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this, config.getServletContext()); + SpringBeanAutowiringSupport + .processInjectionBasedOnServletContext(this, config.getServletContext()); } @Override - public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { + public void doGet(HttpServletRequest request, HttpServletResponse response) + throws ServletException, IOException { + String endpointKey = URLDecoder.decode(request.getParameter(ENDPOINT_KEY_PARAMETER), "UTF-8"); - String profileTypeString = URLDecoder.decode(request.getParameter(PROFILE_TYPE_PARAMETER), "UTF-8"); + String profileTypeString = URLDecoder.decode(request.getParameter(PROFILE_TYPE_PARAMETER), + "UTF-8"); + ProfileType profileType = ProfileType.valueOf(profileTypeString); try { EndpointProfileDto profile = profileService.getEndpointProfileByKeyHash(endpointKey); String json; - String fileName = MessageFormatter.arrayFormat(PROFILE_FILE_NAME_PATTERN, - new Object[]{endpointKey, profileType.name().toLowerCase(), System.currentTimeMillis()}).getMessage(); + String fileName = MessageFormatter + .arrayFormat( + PROFILE_FILE_NAME_PATTERN, + new Object[]{ + endpointKey, profileType.name().toLowerCase(), System.currentTimeMillis() + }) + .getMessage(); + if (profileType == ProfileType.CLIENT) { json = profile.getClientProfileBody(); } else { @@ -85,16 +96,21 @@ public void doGet(HttpServletRequest request, HttpServletResponse response) thro json = "{}"; } Object jsonObject = FORMATTER.readValue(json, Object.class); - byte[] body = FORMATTER.writerWithDefaultPrettyPrinter().writeValueAsString(jsonObject).getBytes("UTF-8"); + byte[] body = FORMATTER + .writerWithDefaultPrettyPrinter() + .writeValueAsString(jsonObject) + .getBytes("UTF-8"); + ServletUtils.prepareDisposition(request, response, fileName); response.setContentType(JSON); response.setContentLength(body.length); response.setBufferSize(BUFFER); response.getOutputStream().write(body); response.flushBuffer(); - } catch (Exception e) { - LOG.error("Unexpected error in ProfileDownloadServlet.doGet: ", e); - response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Unable to get file: " + e.getMessage()); + } catch (Exception ex) { + LOG.error("Unexpected error in ProfileDownloadServlet.doGet: ", ex); + response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, + "Unable to get file: " + ex.getMessage()); } } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/loadmgmt/DynamicLoadManager.java b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/loadmgmt/DynamicLoadManager.java index 2859f0934e..8cc04d3782 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/loadmgmt/DynamicLoadManager.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/loadmgmt/DynamicLoadManager.java @@ -16,6 +16,7 @@ package org.kaaproject.kaa.server.control.service.loadmgmt; +import static java.text.MessageFormat.format; import static org.kaaproject.kaa.server.common.zk.ServerNameUtil.getNameFromConnectionInfo; import org.apache.thrift.TException; @@ -54,31 +55,32 @@ */ public class DynamicLoadManager implements OperationsNodeListener, BootstrapNodeListener { - /** - * The Constant DEFAULT_PRIORITY. - */ + private static final int DEFAULT_PRIORITY = 10; private static final Logger LOG = LoggerFactory.getLogger(DynamicLoadManager.class); + /** * Map to store Operations servers, key - DNS name host:port. */ private final Map opsServersMap; + /** * Map to store bootstrap services, key - DNS name host:port. */ private final Map bootstrapsMap; - /** - * LoadDistributeonServiceImpl. - */ + + private LoadDistributionService loadDistributionService; + /** * The last bootstrap services update failed. */ private boolean lastBootstrapServersUpdateFailed = false; + /** * Time to live of Operations server load history, in ms. */ - private long opsLoadHistoryTTL = 600000; + private long opsLoadHistoryTtl = 600000; /** * The Constructor. @@ -90,14 +92,17 @@ public DynamicLoadManager(LoadDistributionService loadDistributionService) { opsServersMap = new ConcurrentHashMap(); bootstrapsMap = new ConcurrentHashMap(); // Translate seconds to ms - opsLoadHistoryTTL = loadDistributionService.getOpsServerHistoryTTL() * 1000; + opsLoadHistoryTtl = loadDistributionService.getOpsServerHistoryTTL() * 1000; } /** * Run recalculate process for Operations server Load optimization. */ public void recalculate() { - LOG.info("DynamicLoadManager recalculate() started... lastBootstrapServersUpdateFailed {}", lastBootstrapServersUpdateFailed); + + LOG.info("DynamicLoadManager recalculate() started... lastBootstrapServersUpdateFailed {}", + lastBootstrapServersUpdateFailed); + if (lastBootstrapServersUpdateFailed) { LOG.trace("Registred {} Bootstrap servers", bootstrapsMap.size()); lastBootstrapServersUpdateFailed = false; @@ -106,17 +111,21 @@ public void recalculate() { } } if (loadDistributionService.getRebalancer() != null) { - Map opsServerHistory = new HashMap(); + Map opsServerHistory = new HashMap<>(); for (Integer accessPointId : opsServersMap.keySet()) { opsServerHistory.put(accessPointId, opsServersMap.get(accessPointId).history); } - Map> rules = loadDistributionService.getRebalancer().recalculate(opsServerHistory); + Map> rules = loadDistributionService + .getRebalancer() + .recalculate(opsServerHistory); LOG.trace("DynamicLoadManager recalculate() got {} redirection rules", rules.size()); for (Integer accessPointId : rules.keySet()) { if (opsServersMap.containsKey(accessPointId)) { - sendRedirectionRule(accessPointId, opsServersMap.get(accessPointId).nodeInfo, rules.get(accessPointId)); + sendRedirectionRule(accessPointId, opsServersMap.get(accessPointId).nodeInfo, + rules.get(accessPointId)); } else { - LOG.error("Operations server {} redirection rule exist, but NO server available, skip setting rule.", accessPointId); + LOG.error("Operations server {} redirection rule exist, " + + "but NO server available, skip setting rule.", accessPointId); } } } @@ -144,6 +153,7 @@ public void deregisterListeners() { pm.removeListener((BootstrapNodeListener) this); } + /* * (non-Javadoc) * @@ -160,59 +170,50 @@ public void onNodeAdded(BootstrapNodeInfo nodeInfo) { } /* - * (non-Javadoc) - * - * @see org.kaaproject.kaa.server.common.zk.bootstrap.BootstrapNodeListener# - * onNodeUpdated(org.kaaproject.kaa.server.common.zk.gen.BootstrapNodeInfo) - */ - @Override - public void onNodeUpdated(BootstrapNodeInfo nodeInfo) { - String dnsName = getNameFromConnectionInfo(nodeInfo.getConnectionInfo()); - LOG.info("Bootstrap server {} updated", dnsName); - bootstrapsMap.put(dnsName, nodeInfo); - } - - /* - * (non-Javadoc) - * - * @see org.kaaproject.kaa.server.common.zk.bootstrap.BootstrapNodeListener# - * onNodeRemoved(org.kaaproject.kaa.server.common.zk.gen.BootstrapNodeInfo) - */ - @Override - public void onNodeRemoved(BootstrapNodeInfo nodeInfo) { - String dnsName = getNameFromConnectionInfo(nodeInfo.getConnectionInfo()); - LOG.info("Bootstrap server {} removed", dnsName); - bootstrapsMap.remove(dnsName); - } - - /* - * (non-Javadoc) - * - * @see - * org.kaaproject.kaa.server.common.zk.operations.OperationsNodeListener - * #onNodeAdded(org.kaaproject.kaa.server.common.zk.gen.OperationsNodeInfo) - */ + * (non-Javadoc) + * + * @see + * org.kaaproject.kaa.server.common.zk.operations.OperationsNodeListener + * #onNodeAdded(org.kaaproject.kaa.server.common.zk.gen.OperationsNodeInfo) + */ @Override public void onNodeAdded(OperationsNodeInfo nodeInfo) { String dnsName = getNameFromConnectionInfo(nodeInfo.getConnectionInfo()); int accessPointId = ServerNameUtil.crc32(nodeInfo.getConnectionInfo()); addNewOperationsServer(accessPointId, dnsName, nodeInfo); - LOG.info("Operations server [{}][{}] added. Updating {} Bootstrap servers", accessPointId, dnsName, bootstrapsMap.size()); + LOG.info("Operations server [{}][{}] added. Updating {} Bootstrap servers", + accessPointId, dnsName, bootstrapsMap.size()); + for (BootstrapNodeInfo bootstrapNodeInfo : bootstrapsMap.values()) { updateBootstrap(bootstrapNodeInfo); } } + /* * (non-Javadoc) * - * @see - * org.kaaproject.kaa.server.common.zk.operations.OperationsNodeListener - * #onNodeUpdated - * (org.kaaproject.kaa.server.common.zk.gen.OperationsNodeInfo) + * @see org.kaaproject.kaa.server.common.zk.bootstrap.BootstrapNodeListener# + * onNodeUpdated(org.kaaproject.kaa.server.common.zk.gen.BootstrapNodeInfo) */ @Override + public void onNodeUpdated(BootstrapNodeInfo nodeInfo) { + String dnsName = getNameFromConnectionInfo(nodeInfo.getConnectionInfo()); + LOG.info("Bootstrap server {} updated", dnsName); + bootstrapsMap.put(dnsName, nodeInfo); + } + + + /* + * (non-Javadoc) + * + * @see + * org.kaaproject.kaa.server.common.zk.operations.OperationsNodeListener + * #onNodeUpdated + * (org.kaaproject.kaa.server.common.zk.gen.OperationsNodeInfo) + */ + @Override public void onNodeUpdated(OperationsNodeInfo nodeInfo) { String dnsName = getNameFromConnectionInfo(nodeInfo.getConnectionInfo()); int accessPointId = ServerNameUtil.crc32(nodeInfo.getConnectionInfo()); @@ -224,15 +225,17 @@ public void onNodeUpdated(OperationsNodeInfo nodeInfo) { } } - /** - * @param dnsName - * @param nodeInfo + /* + * (non-Javadoc) + * + * @see org.kaaproject.kaa.server.common.zk.bootstrap.BootstrapNodeListener# + * onNodeRemoved(org.kaaproject.kaa.server.common.zk.gen.BootstrapNodeInfo) */ - private void addNewOperationsServer(int accessPointId, String dnsName, OperationsNodeInfo nodeInfo) { - OperationsServerMeta meta = new OperationsServerMeta(null, nodeInfo); - ThriftOperationsServer operations = new ThriftOperationsServer(dnsName, DEFAULT_PRIORITY); - meta.opsServer = operations; - opsServersMap.put(accessPointId, meta); + @Override + public void onNodeRemoved(BootstrapNodeInfo nodeInfo) { + String dnsName = getNameFromConnectionInfo(nodeInfo.getConnectionInfo()); + LOG.info("Bootstrap server {} removed", dnsName); + bootstrapsMap.remove(dnsName); } /* @@ -249,12 +252,24 @@ public void onNodeRemoved(OperationsNodeInfo nodeInfo) { int accessPointId = ServerNameUtil.crc32(nodeInfo.getConnectionInfo()); opsServersMap.remove(accessPointId); - LOG.info("Operations server [{}][{}] removed. Updating {} Bootstrap servers", accessPointId, dnsName, bootstrapsMap.size()); + LOG.info("Operations server [{}][{}] removed. Updating {} Bootstrap servers", + accessPointId, dnsName, bootstrapsMap.size()); + for (BootstrapNodeInfo bootstrapNodeInfo : bootstrapsMap.values()) { updateBootstrap(bootstrapNodeInfo); } } + + private void addNewOperationsServer(int accessPointId, String dnsName, + OperationsNodeInfo nodeInfo) { + OperationsServerMeta meta = new OperationsServerMeta(null, nodeInfo); + meta.opsServer = new ThriftOperationsServer(dnsName, DEFAULT_PRIORITY); + opsServersMap.put(accessPointId, meta); + } + + + /** * Gets the load distribution service. * @@ -282,41 +297,52 @@ private void updateBootstrap(BootstrapNodeInfo nodeInfo) { final String dnsName = getNameFromConnectionInfo(nodeInfo.getConnectionInfo()); LOG.debug("Update bootstrap service: {}", dnsName); try { - ThriftClient client = new ThriftClient(nodeInfo - .getConnectionInfo().getThriftHost().toString(), nodeInfo.getConnectionInfo().getThriftPort(), KaaThriftService.BOOTSTRAP_SERVICE, - BootstrapThriftService.Client.class); - client.setThriftActivity(new ThriftActivity() { + ThriftClient thriftClient = new ThriftClient<>( + nodeInfo.getConnectionInfo().getThriftHost().toString(), + nodeInfo.getConnectionInfo().getThriftPort(), + KaaThriftService.BOOTSTRAP_SERVICE, + BootstrapThriftService.Client.class + ); + + thriftClient.setThriftActivity(new ThriftActivity() { @Override public void isSuccess(boolean activitySuccess) { lastBootstrapServersUpdateFailed = !activitySuccess; - LOG.info("Bootstrap {}: Operations services list updated {}", dnsName, activitySuccess ? "successfully" - : "unsuccessfully"); + LOG.info("Bootstrap {}: Operations services list updated {}", dnsName, + activitySuccess ? "successfully" : "unsuccessfully"); } @Override - public void doInTemplate(Client t) { + public void doInTemplate(Client client) { try { // NOSONAR List operationsServersList = new ArrayList<>(); for (Integer accessPointId : opsServersMap.keySet()) { operationsServersList.add(opsServersMap.get(accessPointId).opsServer); - LOG.trace("Bootstrap {} server: {}", dnsName, opsServersMap.get(accessPointId).opsServer.toString()); + LOG.trace("Bootstrap {} server: {}", + dnsName, opsServersMap.get(accessPointId).opsServer.toString()); } - LOG.trace("Bootstrap {} Operations servers list size {} ready to updates", dnsName, operationsServersList.size()); - t.onOperationsServerListUpdate(operationsServersList); + LOG.trace("Bootstrap {} Operations servers list size {} ready to updates", + dnsName, operationsServersList.size()); + client.onOperationsServerListUpdate(operationsServersList); LOG.info("Bootstrap {} Operations servers list updated.", dnsName); - } catch (TException e) { + } catch (TException ex) { lastBootstrapServersUpdateFailed = true; - LOG.error(MessageFormat.format("Bootstrap Operations servers list updated failed", dnsName), e); + LOG.error(format("Bootstrap Operations servers list updated failed", dnsName), ex); } } }); - ThriftExecutor.execute(client); - } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { + ThriftExecutor.execute(thriftClient); + } catch (NoSuchMethodException + | SecurityException + | InstantiationException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException ex) { lastBootstrapServersUpdateFailed = true; - LOG.error(MessageFormat.format("Bootstrap {0} Operations services list execute updated failed", dnsName), e); + LOG.error(format("Bootstrap {0} Operations services list execute updated failed", dnsName), + ex); } } @@ -327,58 +353,71 @@ public void doInTemplate(Client t) { * @param nodeInfo the node info * @param rules the list of redirection rules */ - private void sendRedirectionRule(final Integer accessPointId, OperationsNodeInfo nodeInfo, final List rules) { - LOG.trace("Set redirection rule for Operations server: {}; Thrift: {}:{}", accessPointId, nodeInfo.getConnectionInfo() - .getThriftHost().toString(), nodeInfo.getConnectionInfo().getThriftPort()); + private void sendRedirectionRule(final Integer accessPointId, OperationsNodeInfo nodeInfo, + final List rules) { + LOG.trace("Set redirection rule for Operations server: {}; Thrift: {}:{}", + accessPointId, nodeInfo.getConnectionInfo().getThriftHost().toString(), + nodeInfo.getConnectionInfo().getThriftPort()); try { - ThriftClient client = new ThriftClient(nodeInfo - .getConnectionInfo().getThriftHost().toString(), nodeInfo.getConnectionInfo().getThriftPort(), KaaThriftService.OPERATIONS_SERVICE, - OperationsThriftService.Client.class); - client.setThriftActivity(new ThriftActivity() { + + ThriftClient thriftClient = new ThriftClient<>( + nodeInfo.getConnectionInfo().getThriftHost().toString(), + nodeInfo.getConnectionInfo().getThriftPort(), + KaaThriftService.OPERATIONS_SERVICE, + OperationsThriftService.Client.class + ); + + thriftClient.setThriftActivity(new ThriftActivity() { @Override public void isSuccess(boolean activitySuccess) { - LOG.info("Operations server {} redirection rule set {}", accessPointId, activitySuccess ? "successfully" - : "unsuccessfully"); + LOG.info("Operations server {} redirection rule set {}", accessPointId, + activitySuccess ? "successfully" : "unsuccessfully"); } @Override - public void doInTemplate(org.kaaproject.kaa.server.common.thrift.gen.operations.OperationsThriftService.Client t) { + public void doInTemplate(OperationsThriftService.Client client) { try { // NOSONAR for (RedirectionRule rule : rules) { - t.setRedirectionRule(rule); - LOG.info("Operations {} set redirection rule: {} <> {}, {}", accessPointId, rule.getAccessPointId(), - rule.getInitRedirectProbability(), rule.getSessionRedirectProbability()); + client.setRedirectionRule(rule); + LOG.info("Operations {} set redirection rule: {} <> {}, {}", + accessPointId, rule.getAccessPointId(), rule.getInitRedirectProbability(), + rule.getSessionRedirectProbability()); } - } catch (TException e) { - LOG.error(MessageFormat.format("Operations server {0} set redirection rule failed", accessPointId), e); + } catch (TException ex) { + LOG.error(format("Operations server {0} set redirection rule failed", accessPointId), + ex); } } }); - ThriftExecutor.execute(client); - } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException - | InvocationTargetException e) { - LOG.error(MessageFormat.format("Operations server {0} set redirection rule failed", accessPointId), e); + ThriftExecutor.execute(thriftClient); + } catch (NoSuchMethodException + | SecurityException + | InstantiationException + | IllegalAccessException + | IllegalArgumentException + | InvocationTargetException ex) { + LOG.error(format("Operations server {0} set redirection rule failed", accessPointId), ex); } } /** * Gets the operations Server history TTL. * - * @return the opsLoadHistoryTTL + * @return the opsLoadHistoryTtl */ - public long getOpsServerHistoryTTL() { - return opsLoadHistoryTTL; + public long getOpsServerHistoryTtl() { + return opsLoadHistoryTtl; } /** * Sets the operations history TTL. * - * @param opsServerHistoryTTL the opsLoadHistoryTTL to set + * @param opsServerHistoryTtl the opsLoadHistoryTtl to set */ - public void setOpsServerHistoryTTL(long opsServerHistoryTTL) { - this.opsLoadHistoryTTL = opsServerHistoryTTL; + public void setOpsServerHistoryTtl(long opsServerHistoryTtl) { + this.opsLoadHistoryTtl = opsServerHistoryTtl; } /** @@ -391,19 +430,14 @@ public Rebalancer getDynamicRebalancer() { } class OperationsServerMeta { - /** - * The Operations Server - */ + + public ThriftOperationsServer opsServer; - /** - * The history. - */ + public OperationsServerLoadHistory history; - /** - * The node info. - */ + public OperationsNodeInfo nodeInfo; /** @@ -415,7 +449,7 @@ class OperationsServerMeta { public OperationsServerMeta(ThriftOperationsServer opsServer, OperationsNodeInfo nodeInfo) { this.opsServer = opsServer; this.nodeInfo = nodeInfo; - history = new OperationsServerLoadHistory(opsLoadHistoryTTL); + history = new OperationsServerLoadHistory(opsLoadHistoryTtl); history.addOpsServerLoad(nodeInfo.getLoadInfo()); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/loadmgmt/dynamicmgmt/EndpointCountRebalancer.java b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/loadmgmt/dynamicmgmt/EndpointCountRebalancer.java index ca102dc3c0..10ec4e5b81 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/loadmgmt/dynamicmgmt/EndpointCountRebalancer.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/loadmgmt/dynamicmgmt/EndpointCountRebalancer.java @@ -30,6 +30,7 @@ import java.util.List; import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import java.util.concurrent.atomic.AtomicLong; @Service @@ -40,22 +41,26 @@ public class EndpointCountRebalancer implements Rebalancer { private static final double DEFAULT_MIN_INIT_REDIRECT = 0.75; private static final double DEFAULT_MIN_SESSION_REDIRECT = 0.0; private final AtomicLong ruleIdSeq = new AtomicLong(); + /** * Minimum difference between amount of endpoints that need to be present in - * order to trigger rebalancing + * order to trigger rebalancing. */ @Value("#{properties[loadmgmt_min_diff]}") private int minDiff = DEFAULT_MIN_DIFF; + /** - * Maximum redirect probability for new sessions + * Maximum redirect probability for new sessions. */ @Value("#{properties[loadmgmt_max_init_redirect_probability]}") private double maxInitRedirectProbability = DEFAULT_MIN_INIT_REDIRECT; + /** - * Maximum redirect probability for existing sessions + * Maximum redirect probability for existing sessions. */ @Value("#{properties[loadmgmt_max_session_redirect_probability]}") private double maxSessionRedirectProbability = DEFAULT_MIN_SESSION_REDIRECT; + /** * Load mgmt data recalculation period. */ @@ -63,7 +68,9 @@ public class EndpointCountRebalancer implements Rebalancer { private int recalculationPeriod; @Override - public Map> recalculate(Map opsServerLoadHistory) { + public Map> recalculate( + Map opsServerLoadHistory) { + Map> result = new HashMap<>(); if (opsServerLoadHistory.isEmpty()) { LOG.debug("No ops server load history yet"); @@ -73,12 +80,16 @@ public Map> recalculate(Map accessPointHistory : opsServerLoadHistory.entrySet()) { - LOG.debug("Access point: {} has {} history items", accessPointHistory.getKey(), accessPointHistory.getValue().getHistory().size()); + Set> entries = opsServerLoadHistory.entrySet(); + for (Entry accessPointHistory : entries) { + LOG.debug("Access point: {} has {} history items", + accessPointHistory.getKey(), accessPointHistory.getValue().getHistory().size()); + for (OperationsServerLoad load : accessPointHistory.getValue().getHistory()) { LOG.debug("History: {}", load); } } + int minLoadedOpsServer = getMinLoadedOpsServer(opsServerLoadHistory); int minEndpointCount = getLastEndpointCount(opsServerLoadHistory.get(minLoadedOpsServer)); int maxLoadedOpsServer = getMaxLoadedOpsServer(opsServerLoadHistory); @@ -88,7 +99,8 @@ public Map> recalculate(Map> recalculate(Map 0 || sessionRedirectProbability > 0) { - RedirectionRule rule = new RedirectionRule(targetWeight.getKey(), ruleIdSeq.getAndIncrement(), initRedirectProbability, + + RedirectionRule rule = new RedirectionRule(targetWeight.getKey(), + ruleIdSeq.getAndIncrement(), initRedirectProbability, sessionRedirectProbability, recalculationPeriod * 1000L); LOG.debug("Calculated new rule for accessPointId: {} -> {}", opsEntry.getKey(), rule); redirectionRules.add(rule); @@ -128,9 +144,10 @@ public Map> recalculate(Map calculateWeights(Map opsServerLoadHistory, int targetLoad) { - Map weights = new LinkedHashMap<>(); + private Map calculateWeights( + Map opsServerLoadHistory, int targetLoad) { + Map weights = new LinkedHashMap<>(); double totalPosWeight = 0; double totalNegWeight = 0; for (Entry opsEntry : opsServerLoadHistory.entrySet()) { @@ -150,12 +167,15 @@ private Map calculateWeights(Map opsServerLoadHistory) { + private int getMinLoadedOpsServer( + Map opsServerLoadHistory) { + int result = 0; int minCount = Integer.MAX_VALUE; for (Entry entry : opsServerLoadHistory.entrySet()) { @@ -168,7 +188,8 @@ private int getMinLoadedOpsServer(Map opsS return result; } - private int getMaxLoadedOpsServer(Map opsServerLoadHistory) { + private int getMaxLoadedOpsServer( + Map opsServerLoadHistory) { int result = 0; int maxCount = Integer.MIN_VALUE; for (Entry entry : opsServerLoadHistory.entrySet()) { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/CSdkGenerator.java b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/CSdkGenerator.java index b8255c97f1..f42ff6259a 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/CSdkGenerator.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/CSdkGenerator.java @@ -82,8 +82,11 @@ public class CSdkGenerator extends SdkGenerator { private static final String LOGGING_HEADER = KAA_GEN_SOURCE_DIR + "kaa_logging_definitions.h"; private static final String PROFILE_HEADER = KAA_GEN_SOURCE_DIR + "kaa_profile_definitions.h"; - private static final String CONFIGURATION_HEADER = KAA_GEN_SOURCE_DIR + "kaa_configuration_definitions.h"; - private static final String NOTIFICATION_HEADER = KAA_GEN_SOURCE_DIR + "kaa_notification_definitions.h"; + private static final String CONFIGURATION_HEADER = KAA_GEN_SOURCE_DIR + + "kaa_configuration_definitions.h"; + + private static final String NOTIFICATION_HEADER = KAA_GEN_SOURCE_DIR + + "kaa_notification_definitions.h"; private static final String PROFILE_SOURCE_NAME_PATTERN = "kaa_profile_gen"; private static final String LOGGING_SOURCE_NAME_PATTERN = "kaa_logging_gen"; @@ -101,17 +104,26 @@ public CSdkGenerator() { velocityEngine = new VelocityEngine(); velocityEngine.addProperty("resource.loader", "class, file"); + velocityEngine.addProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader"); + velocityEngine.addProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.FileResourceLoader"); velocityEngine.addProperty("file.resource.loader.path", "/, ."); velocityEngine.setProperty("runtime.references.strict", true); - velocityEngine.setProperty("runtime.log.logsystem.class", "org.apache.velocity.runtime.log.NullLogSystem"); + + velocityEngine.setProperty("runtime.log.logsystem.class", + "org.apache.velocity.runtime.log.NullLogSystem"); } /* (non-Javadoc) - * @see org.kaaproject.kaa.server.control.service.sdk.SdkGenerator#generateSdk(java.lang.String, java.util.List, java.lang.String, int, int, int, java.lang.String, java.lang.String, java.lang.String, byte[], java.util.List) + * @see org.kaaproject.kaa.server.control.service.sdk.SdkGenerator#generateSdk( + * java.lang.String, java.util.List, + * java.lang.String, int, + * int, int, + * java.lang.String, java.lang.String, + * java.lang.String, byte[], java.util.List) */ @Override public FileData generateSdk(String buildVersion, @@ -129,7 +141,8 @@ public FileData generateSdk(String buildVersion, Integer profileSchemaVersion = sdkProfile.getProfileSchemaVersion(); String defaultVerifierToken = sdkProfile.getDefaultVerifierToken(); - String sdkTemplateLocation = Environment.getServerHomeDir() + "/" + C_SDK_DIR + "/" + C_SDK_PREFIX + buildVersion + ".tar.gz"; + String sdkTemplateLocation = Environment.getServerHomeDir() + "/" + C_SDK_DIR + "/" + + C_SDK_PREFIX + buildVersion + ".tar.gz"; LOG.debug("Lookup C SDK template: {}", sdkTemplateLocation); @@ -139,44 +152,48 @@ public FileData generateSdk(String buildVersion, CompressorInputStream cis = csf.createCompressorInputStream(CompressorStreamFactory.GZIP, new FileInputStream(sdkTemplateLocation)); - ArchiveInputStream templateArchive = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, cis); + final ArchiveInputStream templateArchive = asf.createArchiveInputStream( + ArchiveStreamFactory.TAR, cis + ); ByteArrayOutputStream sdkOutput = new ByteArrayOutputStream(); - CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, sdkOutput); + CompressorOutputStream cos = csf.createCompressorOutputStream( + CompressorStreamFactory.GZIP, sdkOutput); + ArchiveOutputStream sdkFile = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, cos); - Map replacementData = new HashMap(); + Map replacementData = new HashMap<>(); - List cSources = new ArrayList<>(); + List sources = new ArrayList<>(); if (!StringUtils.isBlank(profileSchemaBody)) { - cSources.addAll(generateProfileSources(profileSchemaBody)); + sources.addAll(generateProfileSources(profileSchemaBody)); } if (!StringUtils.isBlank(logSchemaBody)) { - cSources.addAll(generateLogSources(logSchemaBody)); + sources.addAll(generateLogSources(logSchemaBody)); } if (!StringUtils.isBlank(configurationBaseSchemaBody)) { - cSources.addAll(generateConfigurationSources(configurationBaseSchemaBody)); + sources.addAll(generateConfigurationSources(configurationBaseSchemaBody)); } if (!StringUtils.isBlank(notificationSchemaBody)) { - cSources.addAll(generateNotificationSources(notificationSchemaBody)); + sources.addAll(generateNotificationSources(notificationSchemaBody)); } if (eventFamilies != null && !eventFamilies.isEmpty()) { - cSources.addAll(CEventSourcesGenerator.generateEventSources(eventFamilies)); + sources.addAll(CEventSourcesGenerator.generateEventSources(eventFamilies)); } - for (TarEntryData entryData : cSources) { + for (TarEntryData entryData : sources) { replacementData.put(entryData.getEntry().getName(), entryData); } - ArchiveEntry e = null; - while ((e = templateArchive.getNextEntry()) != null) { - if (!e.isDirectory()) { - if (e.getName().equals(KAA_DEFAULTS_HEADER)) { + ArchiveEntry archiveEntry; + while ((archiveEntry = templateArchive.getNextEntry()) != null) { + if (!archiveEntry.isDirectory()) { + if (archiveEntry.getName().equals(KAA_DEFAULTS_HEADER)) { // TODO: eliminate schema versions and substitute them for a single sdkToken byte[] kaaDefaultsData = generateKaaDefaults(bootstrapNodes, sdkToken, profileSchemaVersion, @@ -188,10 +205,10 @@ public FileData generateSdk(String buildVersion, kaaDefaultsEntry.setSize(kaaDefaultsData.length); sdkFile.putArchiveEntry(kaaDefaultsEntry); sdkFile.write(kaaDefaultsData); - } else if (e.getName().equals(KAA_CMAKEGEN)) { + } else if (archiveEntry.getName().equals(KAA_CMAKEGEN)) { // Ignore duplicate source names List sourceNames = new LinkedList<>(); - for (TarEntryData sourceEntry : cSources) { + for (TarEntryData sourceEntry : sources) { String fileName = sourceEntry.getEntry().getName(); if (fileName.endsWith(C_SOURCE_SUFFIX) && !sourceNames.contains(fileName)) { sourceNames.add(fileName); @@ -200,22 +217,23 @@ public FileData generateSdk(String buildVersion, VelocityContext context = new VelocityContext(); context.put("sourceNames", sourceNames); - String cSourceData = generateSourceFromTemplate(TEMPLATE_DIR + File.separator + "CMakeGen.vm", context); + String sourceData = generateSourceFromTemplate(TEMPLATE_DIR + + File.separator + "CMakeGen.vm", context); TarArchiveEntry kaaCMakeEntry = new TarArchiveEntry(KAA_CMAKEGEN); - kaaCMakeEntry.setSize(cSourceData.length()); + kaaCMakeEntry.setSize(sourceData.length()); sdkFile.putArchiveEntry(kaaCMakeEntry); - sdkFile.write(cSourceData.getBytes()); - } else if (replacementData.containsKey(e.getName())) { - TarEntryData entryData = replacementData.remove(e.getName()); + sdkFile.write(sourceData.getBytes()); + } else if (replacementData.containsKey(archiveEntry.getName())) { + TarEntryData entryData = replacementData.remove(archiveEntry.getName()); sdkFile.putArchiveEntry(entryData.getEntry()); sdkFile.write(entryData.getData()); } else { - sdkFile.putArchiveEntry(e); + sdkFile.putArchiveEntry(archiveEntry); IOUtils.copy(templateArchive, sdkFile); } } else { - sdkFile.putArchiveEntry(e); + sdkFile.putArchiveEntry(archiveEntry); } sdkFile.closeArchiveEntry(); @@ -242,21 +260,26 @@ public FileData generateSdk(String buildVersion, return sdk; } - private List generateSourcesFromSchema(Schema schema, String sourceName, String namespace) { + private List generateSourcesFromSchema(Schema schema, String sourceName, + String namespace) { List tarEntries = new LinkedList<>(); try ( OutputStream headerStream = new ByteArrayOutputStream(); - OutputStream sourceStream = new ByteArrayOutputStream(); + OutputStream sourceStream = new ByteArrayOutputStream() ) { Compiler compiler = new CCompiler(schema, sourceName, headerStream, sourceStream); compiler.setNamespacePrefix(namespace); compiler.generate(); - tarEntries.add(createTarEntry(KAA_GEN_SOURCE_DIR + sourceName + C_HEADER_SUFFIX, headerStream.toString())); - tarEntries.add(createTarEntry(KAA_GEN_SOURCE_DIR + sourceName + C_SOURCE_SUFFIX, sourceStream.toString())); - } catch (Exception e) { - LOG.error("Failed to generate C sdk sources", e); + tarEntries.add(createTarEntry(KAA_GEN_SOURCE_DIR + sourceName + C_HEADER_SUFFIX, + headerStream.toString())); + + tarEntries.add(createTarEntry(KAA_GEN_SOURCE_DIR + sourceName + C_SOURCE_SUFFIX, + sourceStream.toString())); + + } catch (Exception ex) { + LOG.error("Failed to generate C sdk sources", ex); } return tarEntries; @@ -317,7 +340,8 @@ private byte[] generateKaaDefaults(List bootstrapNodes, context.put("Integer", Integer.class); context.put("ServerNameUtil", ServerNameUtil.class); - return generateSourceFromTemplate(TEMPLATE_DIR + File.separator + "kaa_defaults.hvm", context).getBytes(); + return generateSourceFromTemplate(TEMPLATE_DIR + File.separator + + "kaa_defaults.hvm", context).getBytes(); } private List generateProfileSources(String profileSchemaBody) { @@ -327,7 +351,8 @@ private List generateProfileSources(String profileSchemaBody) { tarEntries.add(createTarEntry(PROFILE_HEADER, processHeaderTemplate("kaa_profile_definitions.hvm", schema, PROFILE_NAMESPACE))); - tarEntries.addAll(generateSourcesFromSchema(schema, PROFILE_SOURCE_NAME_PATTERN, PROFILE_NAMESPACE)); + tarEntries.addAll(generateSourcesFromSchema(schema, PROFILE_SOURCE_NAME_PATTERN, + PROFILE_NAMESPACE)); return tarEntries; } @@ -339,7 +364,8 @@ private List generateLogSources(String logSchemaBody) { tarEntries.add(createTarEntry(LOGGING_HEADER, processHeaderTemplate("kaa_logging_definitions.hvm", schema, LOGGING_NAMESPACE))); - tarEntries.addAll(generateSourcesFromSchema(schema, LOGGING_SOURCE_NAME_PATTERN, LOGGING_NAMESPACE)); + tarEntries.addAll(generateSourcesFromSchema(schema, LOGGING_SOURCE_NAME_PATTERN, + LOGGING_NAMESPACE)); return tarEntries; } @@ -348,10 +374,16 @@ private List generateConfigurationSources(String configurationSche Schema schema = new Schema.Parser().parse(configurationSchemaBody); List tarEntries = new LinkedList<>(); - tarEntries.add(createTarEntry(CONFIGURATION_HEADER, - processHeaderTemplate("kaa_configuration_definitions.hvm", schema, CONFIGURATION_NAMESPACE))); + tarEntries.add( + createTarEntry( + CONFIGURATION_HEADER, + processHeaderTemplate("kaa_configuration_definitions.hvm", schema, + CONFIGURATION_NAMESPACE) + ) + ); - tarEntries.addAll(generateSourcesFromSchema(schema, CONFIGURATION_SOURCE_NAME_PATTERN, CONFIGURATION_NAMESPACE)); + tarEntries.addAll(generateSourcesFromSchema(schema, + CONFIGURATION_SOURCE_NAME_PATTERN, CONFIGURATION_NAMESPACE)); return tarEntries; } @@ -363,7 +395,8 @@ private List generateNotificationSources(String notificationSchema tarEntries.add(createTarEntry(NOTIFICATION_HEADER, processHeaderTemplate("kaa_notification_definitions.hvm", schema, NOTIFICATION_NAMESPACE))); - tarEntries.addAll(generateSourcesFromSchema(schema, NOTIFICATION_SOURCE_NAME_PATTERN, NOTIFICATION_NAMESPACE)); + tarEntries.addAll(generateSourcesFromSchema(schema, + NOTIFICATION_SOURCE_NAME_PATTERN, NOTIFICATION_NAMESPACE)); return tarEntries; } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/CppSdkGenerator.java b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/CppSdkGenerator.java index 00edb454cd..82b2f24e84 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/CppSdkGenerator.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/CppSdkGenerator.java @@ -57,75 +57,47 @@ */ public class CppSdkGenerator extends SdkGenerator { - /** - * The Constant LOG. - */ - private static final Logger LOG = LoggerFactory - .getLogger(CppSdkGenerator.class); - /** - * The Constant CPP_SDK_DIR. - */ + private static final Logger LOG = LoggerFactory.getLogger(CppSdkGenerator.class); + + private static final String CPP_SDK_DIR = "sdk/cpp"; - /** - * The Constant CPP_SDK_PREFIX. - */ + private static final String CPP_SDK_PREFIX = "kaa-cpp-ep-sdk-"; - /** - * The Constant APPLICATION_TOKEN_VAR. - */ + private static final String SDK_VAR = "%{application.sdk_token}"; - /** - * The Constant SDK_PROFILE_VERSION_VAR. - */ + private static final String SDK_PROFILE_VERSION_VAR = "%{application.profile_version}"; - /** - * The Constant CLIENT_PUB_KEY_LOCATION_VAR. - */ + private static final String CLIENT_PUB_KEY_LOCATION_VAR = "%{application.public_key_location}"; - /** - * The Constant CLIENT_PRIV_KEY_LOCATION_VAR. - */ + private static final String CLIENT_PRIV_KEY_LOCATION_VAR = "%{application.private_key_location}"; - /** - * The Constant CLIENT_STATUS_FILE_LOCATION_VAR. - */ - private static final String CLIENT_STATUS_FILE_LOCATION_VAR = "%{application.status_file_location}"; - /** - * The Constant POLLING_PERIOD_SECONDS_VAR. - */ + private static final String CLIENT_STATUS_FILE_LOCATION_VAR = + "%{application.status_file_location}"; + + private static final String POLLING_PERIOD_SECONDS_VAR = "%{application.polling_period_seconds}"; - /** - * The Constant BOOTSTRAP_SERVERS_INFO_VAR. - */ + private static final String BOOTSTRAP_SERVERS_INFO_VAR = "%{bootstrap_servers_info}"; - /** - * The Constant CONFIG_DATA_DEFAULT_VAR. - */ + private static final String CONFIG_DATA_DEFAULT_VAR = "%{config.data.default}"; - /** - * The Constant BUILD_VERSION. - */ + private static final String BUILD_VERSION = "%{build.version}"; - /** - * The Constant BUILD_COMMIT_HASH. - */ + private static final String BUILD_COMMIT_HASH = "%{build.commit_hash}"; - /** - * The Constant DEFAULT_USER_VERIFIER_TOKEN. - */ + private static final String DEFAULT_USER_VERIFIER_TOKEN = "%{user_verifier_token}"; private static final String SDK_DEFAULTS_TEMPLATE = "sdk/cpp/KaaDefaults.cpp.template"; @@ -134,7 +106,10 @@ public class CppSdkGenerator extends SdkGenerator { private static final String RECORD_CLASS_NAME_VAR = "%{record_class_name}"; private static final String PROFILE_SCHEMA_AVRO_SRC = "avro/profile.avsc"; - private static final String PROFILE_DEFINITIONS_TEMPLATE = "sdk/cpp/profile/ProfileDefinitions.hpp.template"; + + private static final String PROFILE_DEFINITIONS_TEMPLATE = + "sdk/cpp/profile/ProfileDefinitions.hpp.template"; + private static final String PROFILE_DEFINITIONS_PATH = "kaa/profile/gen/ProfileDefinitions.hpp"; private static final String LOG_SCHEMA_AVRO_SRC = "avro/log.avsc"; @@ -142,12 +117,20 @@ public class CppSdkGenerator extends SdkGenerator { private static final String LOG_DEFINITIONS_PATH = "kaa/log/gen/LogDefinitions.hpp"; private static final String NOTIFICATION_SCHEMA_AVRO_SRC = "avro/notification.avsc"; - private static final String NOTIFICATION_DEFINITIONS_TEMPLATE = "sdk/cpp/notification/NotificationDefinitions.hpp.template"; - private static final String NOTIFICATION_DEFINITIONS_PATH = "kaa/notification/gen/NotificationDefinitions.hpp"; + + private static final String NOTIFICATION_DEFINITIONS_TEMPLATE = + "sdk/cpp/notification/NotificationDefinitions.hpp.template"; + + private static final String NOTIFICATION_DEFINITIONS_PATH = + "kaa/notification/gen/NotificationDefinitions.hpp"; private static final String CONFIGURATION_SCHEMA_AVRO_SRC = "avro/configuration.avsc"; - private static final String CONFIGURATION_DEFINITIONS_TEMPLATE = "sdk/cpp/configuration/ConfigurationDefinitions.hpp.template"; - private static final String CONFIGURATION_DEFINITIONS_PATH = "kaa/configuration/gen/ConfigurationDefinitions.hpp"; + + private static final String CONFIGURATION_DEFINITIONS_TEMPLATE = + "sdk/cpp/configuration/ConfigurationDefinitions.hpp.template"; + + private static final String CONFIGURATION_DEFINITIONS_PATH = + "kaa/configuration/gen/ConfigurationDefinitions.hpp"; /** * Replace string. @@ -162,7 +145,12 @@ private static String replaceVar(String body, String variable, String value) { } /* (non-Javadoc) - * @see org.kaaproject.kaa.server.control.service.sdk.SdkGenerator#generateSdk(java.lang.String, java.util.List, java.lang.String, int, int, int, java.lang.String, java.lang.String, java.lang.String, byte[], java.util.List) + * @see org.kaaproject.kaa.server.control.service.sdk.SdkGenerator#generateSdk( + * java.lang.String, java.util.List, + * java.lang.String, int, + * int, int, + * java.lang.String, java.lang.String, + * java.lang.String, byte[], java.util.List) */ @Override public FileData generateSdk(String buildVersion, @@ -178,12 +166,13 @@ public FileData generateSdk(String buildVersion, String sdkToken = sdkProfile.getToken(); Integer configurationSchemaVersion = sdkProfile.getConfigurationSchemaVersion(); - Integer profileSchemaVersion = sdkProfile.getProfileSchemaVersion(); + final Integer profileSchemaVersion = sdkProfile.getProfileSchemaVersion(); Integer notificationSchemaVersion = sdkProfile.getNotificationSchemaVersion(); Integer logSchemaVersion = sdkProfile.getLogSchemaVersion(); String defaultVerifierToken = sdkProfile.getDefaultVerifierToken(); - String sdkTemplateLocation = Environment.getServerHomeDir() + "/" + CPP_SDK_DIR + "/" + CPP_SDK_PREFIX + buildVersion + ".tar.gz"; + String sdkTemplateLocation = Environment.getServerHomeDir() + "/" + CPP_SDK_DIR + + "/" + CPP_SDK_PREFIX + buildVersion + ".tar.gz"; LOG.debug("Lookup Java SDK template: {}", sdkTemplateLocation); @@ -193,10 +182,14 @@ public FileData generateSdk(String buildVersion, CompressorInputStream cis = csf.createCompressorInputStream(CompressorStreamFactory.GZIP, new FileInputStream(sdkTemplateLocation)); - ArchiveInputStream templateArchive = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, cis); + final ArchiveInputStream templateArchive = asf.createArchiveInputStream( + ArchiveStreamFactory.TAR, cis + ); ByteArrayOutputStream sdkOutput = new ByteArrayOutputStream(); - CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, sdkOutput); + CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, + sdkOutput); + ArchiveOutputStream sdkFile = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, cos); Map replacementData = new HashMap<>(); @@ -206,7 +199,9 @@ public FileData generateSdk(String buildVersion, // TODO: remove all version fields and add single sdkToken field // create entry for default properties TarArchiveEntry entry = new TarArchiveEntry(SDK_DEFAULTS_PATH); - byte[] data = generateKaaDefaults(bootstrapNodes, sdkToken, defaultConfigurationData, defaultVerifierToken); + byte[] data = generateKaaDefaults(bootstrapNodes, sdkToken, defaultConfigurationData, + defaultVerifierToken); + entry.setSize(data.length); TarEntryData tarEntry = new TarEntryData(entry, data); cppSources.add(tarEntry); @@ -231,19 +226,19 @@ public FileData generateSdk(String buildVersion, replacementData.put(entryData.getEntry().getName(), entryData); } - ArchiveEntry e = null; - while ((e = templateArchive.getNextEntry()) != null) { - if (!e.isDirectory()) { - if (replacementData.containsKey(e.getName())) { - TarEntryData entryData = replacementData.remove(e.getName()); + ArchiveEntry archiveEntry; + while ((archiveEntry = templateArchive.getNextEntry()) != null) { + if (!archiveEntry.isDirectory()) { + if (replacementData.containsKey(archiveEntry.getName())) { + TarEntryData entryData = replacementData.remove(archiveEntry.getName()); sdkFile.putArchiveEntry(entryData.getEntry()); sdkFile.write(entryData.getData()); } else { - sdkFile.putArchiveEntry(e); + sdkFile.putArchiveEntry(archiveEntry); IOUtils.copy(templateArchive, sdkFile); } } else { - sdkFile.putArchiveEntry(e); + sdkFile.putArchiveEntry(archiveEntry); } sdkFile.closeArchiveEntry(); } @@ -328,7 +323,8 @@ private byte[] generateKaaDefaults(List bootstrapNodes, kaaDefaultsString = replaceVar(kaaDefaultsString, CLIENT_PUB_KEY_LOCATION_VAR, "key.public"); kaaDefaultsString = replaceVar(kaaDefaultsString, CLIENT_PRIV_KEY_LOCATION_VAR, "key.private"); - kaaDefaultsString = replaceVar(kaaDefaultsString, CLIENT_STATUS_FILE_LOCATION_VAR, "kaa.status"); + kaaDefaultsString = replaceVar(kaaDefaultsString, CLIENT_STATUS_FILE_LOCATION_VAR, + "kaa.status"); kaaDefaultsString = replaceVar(kaaDefaultsString, DEFAULT_USER_VERIFIER_TOKEN, @@ -360,7 +356,8 @@ private byte[] generateKaaDefaults(List bootstrapNodes, } kaaDefaultsString = replaceVar(kaaDefaultsString, BOOTSTRAP_SERVERS_INFO_VAR, bootstrapServers); - kaaDefaultsString = replaceVar(kaaDefaultsString, CONFIG_DATA_DEFAULT_VAR, Base64.encodeBase64String(defaultConfigurationData)); + kaaDefaultsString = replaceVar(kaaDefaultsString, CONFIG_DATA_DEFAULT_VAR, + Base64.encodeBase64String(defaultConfigurationData)); return kaaDefaultsString.getBytes(); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/ObjCSdkGenerator.java b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/ObjCSdkGenerator.java index 85e8da2377..2fb158a956 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/ObjCSdkGenerator.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/ObjCSdkGenerator.java @@ -101,7 +101,9 @@ public class ObjCSdkGenerator extends SdkGenerator { private static final String CONFIGURATION_CLASS_VAR = "\\$\\{configuration_class\\}"; private static final String NOTIFICATION_CLASS_VAR = "\\$\\{notification_class\\}"; private static final String LOG_RECORD_CLASS_VAR = "\\$\\{log_record_class\\}"; - private static final String DEFAULT_USER_VERIFIER_TOKEN_VAR = "\\$\\{default_user_verifier_token\\}"; + + private static final String DEFAULT_USER_VERIFIER_TOKEN_VAR = + "\\$\\{default_user_verifier_token\\}"; private static final String PROFILE_NAMESPACE = KAA_SOURCE_PREFIX + "Profile"; private static final String LOGGING_NAMESPACE = KAA_SOURCE_PREFIX + "Logging"; @@ -120,10 +122,11 @@ public FileData generateSdk(String buildVersion, List eventFamilies, String logSchemaBody) throws Exception { - String sdkToken = sdkProperties.getToken(); - String defaultVerifierToken = sdkProperties.getDefaultVerifierToken(); + final String sdkToken = sdkProperties.getToken(); + final String defaultVerifierToken = sdkProperties.getDefaultVerifierToken(); - String sdkTemplateLocation = System.getProperty("server_home_dir") + "/" + SDK_TEMPLATE_DIR + SDK_PREFIX + buildVersion + ".tar.gz"; + String sdkTemplateLocation = System.getProperty("server_home_dir") + + "/" + SDK_TEMPLATE_DIR + SDK_PREFIX + buildVersion + ".tar.gz"; LOG.debug("Lookup Objective C SDK template: {}", sdkTemplateLocation); @@ -133,10 +136,15 @@ public FileData generateSdk(String buildVersion, CompressorInputStream cis = csf.createCompressorInputStream(CompressorStreamFactory.GZIP, new FileInputStream(sdkTemplateLocation)); - ArchiveInputStream templateArchive = asf.createArchiveInputStream(ArchiveStreamFactory.TAR, cis); + final ArchiveInputStream templateArchive = asf.createArchiveInputStream( + ArchiveStreamFactory.TAR, + cis + ); ByteArrayOutputStream sdkOutput = new ByteArrayOutputStream(); - CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, sdkOutput); + CompressorOutputStream cos = csf.createCompressorOutputStream(CompressorStreamFactory.GZIP, + sdkOutput); + ArchiveOutputStream sdkFile = asf.createArchiveOutputStream(ArchiveStreamFactory.TAR, cos); Map replacementData = new HashMap<>(); @@ -148,13 +156,15 @@ public FileData generateSdk(String buildVersion, Schema profileSchema = new Schema.Parser().parse(profileSchemaBody); String profileClassName = PROFILE_NAMESPACE + profileSchema.getName(); - String profileCommonHeader = readResource(PROFILE_TEMPLATE_DIR + PROFILE_COMMON + _H + TEMPLATE_SUFFIX) + String profileCommonHeader = readResource(PROFILE_TEMPLATE_DIR + PROFILE_COMMON + + _H + TEMPLATE_SUFFIX) .replaceAll(PROFILE_CLASS_VAR, profileClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(profileCommonHeader, KAA_ROOT + PROFILE_DIR + PROFILE_COMMON + _H)); - String profileCommonSource = readResource(PROFILE_TEMPLATE_DIR + PROFILE_COMMON + _M + TEMPLATE_SUFFIX) + String profileCommonSource = readResource(PROFILE_TEMPLATE_DIR + PROFILE_COMMON + + _M + TEMPLATE_SUFFIX) .replaceAll(PROFILE_CLASS_VAR, profileClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(profileCommonSource, @@ -181,18 +191,23 @@ public FileData generateSdk(String buildVersion, objcSources.add(CommonSdkUtil.tarEntryForSources(logRecordSource, KAA_ROOT + LOG_DIR + LOG_RECORD + _M)); - String logCollector = readResource(LOG_TEMPLATE_DIR + LOG_COLLECTOR_INTERFACE + TEMPLATE_SUFFIX) + String logCollector = readResource(LOG_TEMPLATE_DIR + + LOG_COLLECTOR_INTERFACE + TEMPLATE_SUFFIX) .replaceAll(LOG_RECORD_CLASS_VAR, logClassName); - objcSources.add(CommonSdkUtil.tarEntryForSources(logCollector, KAA_ROOT + LOG_DIR + LOG_COLLECTOR_INTERFACE)); + objcSources.add(CommonSdkUtil.tarEntryForSources( + logCollector, KAA_ROOT + LOG_DIR + LOG_COLLECTOR_INTERFACE + )); - String logCollectorImplHeader = readResource(LOG_TEMPLATE_DIR + LOG_COLLECTOR_SOURCE + _H + TEMPLATE_SUFFIX) + String logCollectorImplHeader = readResource( + LOG_TEMPLATE_DIR + LOG_COLLECTOR_SOURCE + _H + TEMPLATE_SUFFIX) .replaceAll(LOG_RECORD_CLASS_VAR, logClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(logCollectorImplHeader, KAA_ROOT + LOG_DIR + LOG_COLLECTOR_SOURCE + _H)); - String logCollectorImplSource = readResource(LOG_TEMPLATE_DIR + LOG_COLLECTOR_SOURCE + _M + TEMPLATE_SUFFIX) + String logCollectorImplSource = readResource( + LOG_TEMPLATE_DIR + LOG_COLLECTOR_SOURCE + _M + TEMPLATE_SUFFIX) .replaceAll(LOG_RECORD_CLASS_VAR, logClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(logCollectorImplSource, @@ -207,36 +222,45 @@ public FileData generateSdk(String buildVersion, Schema configurationSchema = new Schema.Parser().parse(configurationBaseSchemaBody); configurationClassName = CONFIGURATION_NAMESPACE + configurationSchema.getName(); - String configurationCommon = readResource(CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_COMMON + TEMPLATE_SUFFIX) + String configurationCommon = readResource( + CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_COMMON + TEMPLATE_SUFFIX) .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName); - objcSources.add(CommonSdkUtil.tarEntryForSources(configurationCommon, KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_COMMON)); + objcSources.add(CommonSdkUtil.tarEntryForSources( + configurationCommon, KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_COMMON + )); - String cfManagerImplHeader = readResource(CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_MANAGER_IMPL + _H + TEMPLATE_SUFFIX) + String cfManagerImplHeader = readResource( + CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_MANAGER_IMPL + _H + TEMPLATE_SUFFIX) .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(cfManagerImplHeader, KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_MANAGER_IMPL + _H)); - String cfManagerImplSource = readResource(CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_MANAGER_IMPL + _M + TEMPLATE_SUFFIX) + String cfManagerImplSource = readResource( + CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_MANAGER_IMPL + _M + TEMPLATE_SUFFIX) .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(cfManagerImplSource, KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_MANAGER_IMPL + _M)); - String cfDeserializerHeader = readResource(CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_DESERIALIZER + _H + TEMPLATE_SUFFIX) + String cfDeserializerHeader = readResource( + CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_DESERIALIZER + _H + TEMPLATE_SUFFIX) .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(cfDeserializerHeader, KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_DESERIALIZER + _H)); - String cfDeserializerSource = readResource(CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_DESERIALIZER + _M + TEMPLATE_SUFFIX) + String cfDeserializerSource = readResource( + CONFIGURATION_TEMPLATE_DIR + CONFIGURATION_DESERIALIZER + _M + TEMPLATE_SUFFIX) .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(cfDeserializerSource, KAA_ROOT + CONFIGURATION_DIR + CONFIGURATION_DESERIALIZER + _M)); - objcSources.addAll(generateSourcesFromSchema(configurationSchema, CONFIGURATION_GEN, CONFIGURATION_NAMESPACE)); + objcSources.addAll( + generateSourcesFromSchema(configurationSchema, CONFIGURATION_GEN, CONFIGURATION_NAMESPACE) + ); } if (StringUtils.isNotBlank(notificationSchemaBody)) { @@ -244,19 +268,23 @@ public FileData generateSdk(String buildVersion, Schema notificationSchema = new Schema.Parser().parse(notificationSchemaBody); String notificationClassName = NOTIFICATION_NAMESPACE + notificationSchema.getName(); - String nfCommonHeader = readResource(NOTIFICATION_TEMPLATE_DIR + NOTIFICATION_COMMON + _H + TEMPLATE_SUFFIX) + String nfCommonHeader = readResource( + NOTIFICATION_TEMPLATE_DIR + NOTIFICATION_COMMON + _H + TEMPLATE_SUFFIX) .replaceAll(NOTIFICATION_CLASS_VAR, notificationClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(nfCommonHeader, KAA_ROOT + NOTIFICATION_DIR + NOTIFICATION_COMMON + _H)); - String nfCommonSource = readResource(NOTIFICATION_TEMPLATE_DIR + NOTIFICATION_COMMON + _M + TEMPLATE_SUFFIX) + String nfCommonSource = readResource( + NOTIFICATION_TEMPLATE_DIR + NOTIFICATION_COMMON + _M + TEMPLATE_SUFFIX) .replaceAll(NOTIFICATION_CLASS_VAR, notificationClassName); objcSources.add(CommonSdkUtil.tarEntryForSources(nfCommonSource, KAA_ROOT + NOTIFICATION_DIR + NOTIFICATION_COMMON + _M)); - objcSources.addAll(generateSourcesFromSchema(notificationSchema, NOTIFICATION_GEN, NOTIFICATION_NAMESPACE)); + objcSources.addAll( + generateSourcesFromSchema(notificationSchema, NOTIFICATION_GEN, NOTIFICATION_NAMESPACE) + ); } if (eventFamilies != null && !eventFamilies.isEmpty()) { @@ -269,21 +297,32 @@ public FileData generateSdk(String buildVersion, objcSources.add(CommonSdkUtil.tarEntryForSources(kaaClient, KAA_ROOT + KAA_CLIENT)); - String baseKaaClientHeader = readResource(SDK_TEMPLATE_DIR + BASE_KAA_CLIENT + _H + TEMPLATE_SUFFIX) + String baseKaaClientHeader = readResource( + SDK_TEMPLATE_DIR + BASE_KAA_CLIENT + _H + TEMPLATE_SUFFIX) .replaceAll(LOG_RECORD_CLASS_VAR, logClassName) .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName); - objcSources.add(CommonSdkUtil.tarEntryForSources(baseKaaClientHeader, KAA_ROOT + BASE_KAA_CLIENT + _H)); - String baseKaaClientSource = readResource(SDK_TEMPLATE_DIR + BASE_KAA_CLIENT + _M + TEMPLATE_SUFFIX) + objcSources.add( + CommonSdkUtil.tarEntryForSources(baseKaaClientHeader, KAA_ROOT + BASE_KAA_CLIENT + _H) + ); + String baseKaaClientSource = readResource( + SDK_TEMPLATE_DIR + BASE_KAA_CLIENT + _M + TEMPLATE_SUFFIX) .replaceAll(LOG_RECORD_CLASS_VAR, logClassName) .replaceAll(CONFIGURATION_CLASS_VAR, configurationClassName); - objcSources.add(CommonSdkUtil.tarEntryForSources(baseKaaClientSource, KAA_ROOT + BASE_KAA_CLIENT + _M)); + objcSources.add( + CommonSdkUtil.tarEntryForSources(baseKaaClientSource, KAA_ROOT + BASE_KAA_CLIENT + _M) + ); - String tokenVerifier = defaultVerifierToken == null ? "nil" : "@\"" + defaultVerifierToken + "\""; - String tokenVerifierSource = readResource(EVENT_TEMPLATE_DIR + USER_VERIFIER_CONSTANTS + TEMPLATE_SUFFIX) + String tokenVerifier = defaultVerifierToken == null ? "nil" : + "@\"" + defaultVerifierToken + "\""; + + String tokenVerifierSource = readResource( + EVENT_TEMPLATE_DIR + USER_VERIFIER_CONSTANTS + TEMPLATE_SUFFIX) .replaceAll(DEFAULT_USER_VERIFIER_TOKEN_VAR, tokenVerifier); - objcSources.add(CommonSdkUtil.tarEntryForSources(tokenVerifierSource, KAA_ROOT + EVENT_DIR + USER_VERIFIER_CONSTANTS)); + + objcSources.add(CommonSdkUtil.tarEntryForSources(tokenVerifierSource, KAA_ROOT + EVENT_DIR + + USER_VERIFIER_CONSTANTS)); String kaaDefaultsTemplate = readResource(SDK_TEMPLATE_DIR + KAA_DEFAULTS + TEMPLATE_SUFFIX); objcSources.add(generateKaaDefaults(kaaDefaultsTemplate, bootstrapNodes, sdkToken, @@ -293,19 +332,19 @@ public FileData generateSdk(String buildVersion, replacementData.put(entryData.getEntry().getName(), entryData); } - ArchiveEntry e; - while ((e = templateArchive.getNextEntry()) != null) { - if (!e.isDirectory()) { - if (replacementData.containsKey(e.getName())) { - TarEntryData entryData = replacementData.remove(e.getName()); + ArchiveEntry archiveEntry; + while ((archiveEntry = templateArchive.getNextEntry()) != null) { + if (!archiveEntry.isDirectory()) { + if (replacementData.containsKey(archiveEntry.getName())) { + TarEntryData entryData = replacementData.remove(archiveEntry.getName()); sdkFile.putArchiveEntry(entryData.getEntry()); sdkFile.write(entryData.getData()); } else { - sdkFile.putArchiveEntry(e); + sdkFile.putArchiveEntry(archiveEntry); IOUtils.copy(templateArchive, sdkFile); } } else { - sdkFile.putArchiveEntry(e); + sdkFile.putArchiveEntry(archiveEntry); } sdkFile.closeArchiveEntry(); } @@ -339,8 +378,9 @@ private TarEntryData generateKaaDefaults(String template, byte[] defaultConfigurationData, SdkProfileDto profileDto) { LOG.debug("Generating kaa defaults"); - final int PROPERTIES_COUNT = 7; - List properties = new ArrayList<>(PROPERTIES_COUNT); + final int propertiesCount = 7; + + List properties = new ArrayList<>(propertiesCount); properties.add(Version.PROJECT_VERSION); properties.add(Version.COMMIT_HASH); properties.add(sdkToken); @@ -349,11 +389,12 @@ private TarEntryData generateKaaDefaults(String template, properties.add(Base64.encodeBase64String(configurationProtocolSchemaBody.getBytes())); properties.add(CommonSdkUtil.bootstrapNodesToString(bootstrapNodes)); - String source = String.format(template, properties.toArray(new Object[PROPERTIES_COUNT])); + String source = String.format(template, properties.toArray(new Object[propertiesCount])); return CommonSdkUtil.tarEntryForSources(source, KAA_ROOT + KAA_DEFAULTS); } - private List generateSourcesFromSchema(Schema schema, String sourceName, String namespace) { + private List generateSourcesFromSchema(Schema schema, String sourceName, + String namespace) { LOG.debug("Generating source with name: " + sourceName); List tarEntries = new LinkedList<>(); @@ -365,10 +406,14 @@ private List generateSourcesFromSchema(Schema schema, String sourc compiler.setNamespacePrefix(namespace); compiler.generate(); - tarEntries.add(CommonSdkUtil.tarEntryForSources(headerStream.toString(), KAA_GEN_FOLDER + sourceName + ".h")); - tarEntries.add(CommonSdkUtil.tarEntryForSources(sourceStream.toString(), KAA_GEN_FOLDER + sourceName + ".m")); - } catch (Exception e) { - LOG.error("Failed to generate ObjectiveC sdk sources", e); + tarEntries.add(CommonSdkUtil.tarEntryForSources(headerStream.toString(), + KAA_GEN_FOLDER + sourceName + ".h")); + + tarEntries.add(CommonSdkUtil.tarEntryForSources(sourceStream.toString(), + KAA_GEN_FOLDER + sourceName + ".m")); + + } catch (Exception ex) { + LOG.error("Failed to generate ObjectiveC sdk sources", ex); } return tarEntries; diff --git a/server/node/src/test/java/org/kaaproject/kaa/server/control/service/loadmgmt/DynamicLoadManagerTest.java b/server/node/src/test/java/org/kaaproject/kaa/server/control/service/loadmgmt/DynamicLoadManagerTest.java index 7ff830fcdf..06ea7f837e 100644 --- a/server/node/src/test/java/org/kaaproject/kaa/server/control/service/loadmgmt/DynamicLoadManagerTest.java +++ b/server/node/src/test/java/org/kaaproject/kaa/server/control/service/loadmgmt/DynamicLoadManagerTest.java @@ -68,7 +68,7 @@ public void testDynamicLoadManager() { assertNotNull(dm.getLoadDistributionService()); assertNotNull(dm.getDynamicRebalancer()); verify(ldServiceMock, atLeast(1)).getOpsServerHistoryTTL(); - assertEquals(300000, dm.getOpsServerHistoryTTL()); + assertEquals(300000, dm.getOpsServerHistoryTtl()); } /** @@ -177,7 +177,7 @@ public void testSetLoadDistributionService() { /** - * Test methods for {@link org.kaaproject.kaa.server.control.service.loadmgmt.DynamicLoadManager#setOpsServerHistoryTTL(long)}. + * Test methods for {@link org.kaaproject.kaa.server.control.service.loadmgmt.DynamicLoadManager#setOpsServerHistoryTtl(long)}. * and {@link org.kaaproject.kaa.server.control.service.loadmgmt.DynamicLoadManager#getOpsServerHistoryTTL(long)} */ @Test @@ -185,8 +185,8 @@ public void testEndpointHistoryTTL() { DynamicLoadManager dm = new DynamicLoadManager(ldServiceMock); assertNotNull(dm); long opsServerHistoryTTL = 123456; - dm.setOpsServerHistoryTTL(opsServerHistoryTTL); - assertEquals(opsServerHistoryTTL, dm.getOpsServerHistoryTTL()); + dm.setOpsServerHistoryTtl(opsServerHistoryTTL); + assertEquals(opsServerHistoryTTL, dm.getOpsServerHistoryTtl()); } }