From 993a6ad0243652191a7ddb4bb79e282783873cf1 Mon Sep 17 00:00:00 2001 From: oklishch Date: Sat, 1 Oct 2016 18:29:47 +0300 Subject: [PATCH] Fixed some warns. --- .../server/operations/pojo/SyncContext.java | 18 +- .../pojo/exceptions/GetDeltaException.java | 6 +- .../service/akka/DefaultAkkaService.java | 20 +- .../ApplicationLogActorMessageProcessor.java | 67 ++++--- .../service/akka/actors/core/TopicActor.java | 43 +++-- .../LocalEndpointActorMessageProcessor.java | 2 +- .../user/LocalUserActorMessageProcessor.java | 8 +- .../akka/utils/EntityConvertUtils.java | 20 +- .../service/cache/AppProfileVersionsKey.java | 18 +- .../service/cache/AppSeqNumber.java | 3 - .../service/cache/CacheService.java | 29 +-- .../service/cache/ConfigurationIdKey.java | 14 +- .../service/cache/DeltaCacheKey.java | 66 +++++-- .../service/cache/EventClassFqnKey.java | 3 - .../service/cache/TopicListCacheEntry.java | 25 ++- .../concurrent/CacheTemporaryMemorizer.java | 47 ++--- .../service/event/DefaultEventService.java | 8 +- ...ionMap.java => EndpointEcfVersionMap.java} | 4 +- .../service/event/EndpointEvent.java | 2 +- .../service/event/EventService.java | 13 +- .../service/event/EventServiceListener.java | 4 +- .../service/event/EventStorage.java | 10 +- .../service/event/GlobalRouteInfo.java | 23 ++- .../service/event/RemoteEndpointEvent.java | 13 +- .../operations/service/event/RouteInfo.java | 12 +- .../operations/service/event/RouteTable.java | 3 + .../service/event/RouteTableAddress.java | 8 +- .../history/DefaultHistoryDeltaService.java | 6 +- .../metrics/DefaultMerticsService.java | 12 +- .../DefaultNotificationDeltaService.java | 77 +++++--- .../NotificationDeltaService.java | 6 +- .../profile/DefaultProfileService.java | 171 ++++++++++-------- .../OperationsFileKeyStoreService.java | 24 +-- .../user/DefaultEndpointUserService.java | 81 ++++++--- .../service/user/EndpointUserService.java | 14 +- ...gration.java => AbstractCtlMigration.java} | 24 ++- .../CtlConfigurationMigration.java | 2 +- .../datamigration/CtlEventsMigration.java | 4 +- .../server/datamigration/CtlLogMigration.java | 2 +- .../CtlNotificationMigration.java | 2 +- .../kaa/server/datamigration/MigrateData.java | 8 +- .../datamigration/UpdateUuidsMigration.java | 2 +- .../datamigration/model/Configuration.java | 48 ++--- .../kaa/server/datamigration/model/Ctl.java | 18 +- .../model/EventSchemaVersion.java | 43 ++--- .../server/datamigration/model/FlatCtl.java | 8 +- .../utils/datadefinition/DataDefinition.java | 33 ++-- 47 files changed, 659 insertions(+), 415 deletions(-) rename server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/{EndpointECFVersionMap.java => EndpointEcfVersionMap.java} (95%) rename server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/{AbstractCTLMigration.java => AbstractCtlMigration.java} (79%) diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/pojo/SyncContext.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/pojo/SyncContext.java index 9c7c847ba2..9a05784559 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/pojo/SyncContext.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/pojo/SyncContext.java @@ -251,20 +251,24 @@ public String toString() { */ public boolean requireImmediateReply() { ServerSync response = getResponse(); - if (response.getProfileSync() != null && response.getProfileSync().getResponseStatus() != SyncResponseStatus.NO_DELTA) { + if (response.getProfileSync() != null + && response.getProfileSync().getResponseStatus() != SyncResponseStatus.NO_DELTA) { return true; } - if (response.getConfigurationSync() != null && response.getConfigurationSync().getResponseStatus() != SyncResponseStatus.NO_DELTA) { + if (response.getConfigurationSync() != null + && response.getConfigurationSync().getResponseStatus() != SyncResponseStatus.NO_DELTA) { return true; } - if (response.getNotificationSync() != null && response.getNotificationSync().getResponseStatus() != SyncResponseStatus.NO_DELTA) { + if (response.getNotificationSync() != null + && response.getNotificationSync().getResponseStatus() != SyncResponseStatus.NO_DELTA) { return true; } if (response.getEventSync() != null) { if (response.getEventSync().getEventSequenceNumberResponse() != null) { return true; } - if (response.getEventSync().getEvents() != null && !response.getEventSync().getEvents().isEmpty()) { + if (response.getEventSync().getEvents() != null + && !response.getEventSync().getEvents().isEmpty()) { return true; } if (response.getEventSync().getEventListenersResponses() != null @@ -274,10 +278,12 @@ public boolean requireImmediateReply() { } if (response.getUserSync() != null) { UserServerSync userResponse = response.getUserSync(); - if (userResponse.getEndpointAttachResponses() != null && !userResponse.getEndpointAttachResponses().isEmpty()) { + if (userResponse.getEndpointAttachResponses() != null + && !userResponse.getEndpointAttachResponses().isEmpty()) { return true; } - if (userResponse.getEndpointDetachResponses() != null && !userResponse.getEndpointDetachResponses().isEmpty()) { + if (userResponse.getEndpointDetachResponses() != null + && !userResponse.getEndpointDetachResponses().isEmpty()) { return true; } if (userResponse.getUserAttachResponse() != null) { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/pojo/exceptions/GetDeltaException.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/pojo/exceptions/GetDeltaException.java index ed46227ad4..56ba9c6359 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/pojo/exceptions/GetDeltaException.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/pojo/exceptions/GetDeltaException.java @@ -41,10 +41,10 @@ public GetDeltaException(String message) { /** * Instantiates a new delta exception. * - * @param e the e + * @param ex exception */ - public GetDeltaException(Exception e) { - super(e); + public GetDeltaException(Exception ex) { + super(ex); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/DefaultAkkaService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/DefaultAkkaService.java index d19216df30..1392e3572b 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/DefaultAkkaService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/DefaultAkkaService.java @@ -102,9 +102,12 @@ public void initActorSystem() { LOG.info("Initializing Akka system..."); akka = ActorSystem.create(EPS, context.getConfig()); LOG.info("Initializing Akka EPS actor..."); - opsActor = akka.actorOf(Props.create(new OperationsServerActor.ActorCreator(context)).withDispatcher(CORE_DISPATCHER_NAME), EPS); + opsActor = akka.actorOf(Props.create( + new OperationsServerActor.ActorCreator(context)) + .withDispatcher(CORE_DISPATCHER_NAME), EPS); LOG.info("Lookup platform protocols"); - Set platformProtocols = PlatformLookup.lookupPlatformProtocols(PlatformLookup.DEFAULT_PROTOCOL_LOOKUP_PACKAGE_NAME); + Set platformProtocols = PlatformLookup.lookupPlatformProtocols( + PlatformLookup.DEFAULT_PROTOCOL_LOOKUP_PACKAGE_NAME); LOG.info("Initializing Akka io router..."); ioRouter = akka.actorOf( new RoundRobinPool(context.getIOWorkerCount()) @@ -156,10 +159,12 @@ public void onRedirectionRule(RedirectionRule redirectionRule) { */ @Override public void onNotification(Notification notification) { - ApplicationDto applicationDto = context.getApplicationService().findAppById(notification.getAppId()); + ApplicationDto applicationDto = context.getApplicationService() + .findAppById(notification.getAppId()); if (applicationDto != null) { LOG.debug("Sending message {} to EPS actor", notification); - opsActor.tell(new ThriftNotificationMessage(applicationDto.getApplicationToken(), notification), ActorRef.noSender()); + opsActor.tell(new ThriftNotificationMessage( + applicationDto.getApplicationToken(), notification), ActorRef.noSender()); } else { LOG.warn("Can't find corresponding application for: {}", notification); } @@ -189,7 +194,8 @@ public void onUserConfigurationUpdate(UserConfigurationUpdate update) { } @Override - public void setStatusListener(final AkkaStatusListener listener, final long statusUpdateFrequency) { + public void setStatusListener(final AkkaStatusListener listener, + final long statusUpdateFrequency) { this.statusListenerThread = new StatusListenerThread(listener, statusUpdateFrequency); this.statusListenerThread.start(); } @@ -218,9 +224,9 @@ public void run() { while (!stopped) { try { Thread.sleep(statusUpdateFrequency); - } catch (InterruptedException e) { + } catch (InterruptedException ex) { if (!stopped) { - LOG.warn("Status update thread was interrupted", e); + LOG.warn("Status update thread was interrupted", ex); } else { break; } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/ApplicationLogActorMessageProcessor.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/ApplicationLogActorMessageProcessor.java index 5514139d7e..ac366c5450 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/ApplicationLogActorMessageProcessor.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/ApplicationLogActorMessageProcessor.java @@ -53,7 +53,8 @@ public class ApplicationLogActorMessageProcessor { /** * The Constant LOG. */ - private static final Logger LOG = LoggerFactory.getLogger(ApplicationLogActorMessageProcessor.class); + private static final Logger LOG = + LoggerFactory.getLogger(ApplicationLogActorMessageProcessor.class); private final LogAppenderService logAppenderService; private final CacheService cacheService; @@ -81,7 +82,9 @@ public ApplicationLogActorMessageProcessor(AkkaContext context, String applicati this.cacheService = context.getCacheService(); this.ctlService = context.getCtlService(); this.applicationToken = applicationToken; - this.applicationId = context.getApplicationService().findAppByApplicationToken(applicationToken).getId(); + this.applicationId = context.getApplicationService() + .findAppByApplicationToken(applicationToken) + .getId(); this.logAppenders = new HashMap<>(); this.logAppendersCache = new HashMap<>(); this.logSchemas = new HashMap<>(); @@ -94,7 +97,8 @@ public ApplicationLogActorMessageProcessor(AkkaContext context, String applicati } protected void processLogEventPack(ActorContext context, LogEventPackMessage message) { - LOG.debug("[{}] Processing a log event pack with {} appenders", applicationToken, logAppenders.size()); + LOG.debug("[{}] Processing a log event pack with {} appenders", + applicationToken, logAppenders.size()); fetchSchemas(message); LogSchema logSchema = message.getLogSchema(); List required = filterAppenders(logSchema.getVersion(), true); @@ -106,15 +110,18 @@ protected void processLogEventPack(ActorContext context, LogEventPackMessage mes } else { LogDeliveryCallback callback; if (required.size() == 1) { - callback = new SingleLogDeliveryCallback(message.getOriginator(), message.getRequestId()); + callback = new SingleLogDeliveryCallback( + message.getOriginator(), message.getRequestId()); } else { - callback = new MultiLogDeliveryCallback(message.getOriginator(), message.getRequestId(), required.size()); + callback = new MultiLogDeliveryCallback( + message.getOriginator(), message.getRequestId(), required.size()); } required.forEach(appender -> { try { appender.doAppend(message.getLogEventPack(), callback); } catch (Exception cause) { - String text = String.format("Failed to append logs using [%s] (ID: %s)", appender.getName(), appender.getAppenderId()); + String text = String.format("Failed to append logs using [%s] (ID: %s)", + appender.getName(), appender.getAppenderId()); LOG.warn(text, cause); sendErrorMessageToEndpoint(message, LogDeliveryErrorCode.APPENDER_INTERNAL_ERROR); } @@ -149,7 +156,8 @@ public List filterAppenders(int schemaVersion, boolean confirmDeliv if (result == null) { result = new ArrayList(); for (LogAppender appender : logAppenders.values()) { - if (appender.isSchemaVersionSupported(schemaVersion) && appender.isDeliveryConfirmationRequired() == confirmDelivery) { + if (appender.isSchemaVersionSupported(schemaVersion) + && appender.isDeliveryConfirmationRequired() == confirmDelivery) { result.add(appender); } } @@ -171,7 +179,8 @@ private void fetchSchemas(LogEventPackMessage message) { EndpointProfileDataDto profileDto = logPack.getProfileDto(); ProfileInfo clientProfile = logPack.getClientProfile(); if (clientProfile == null) { - AppVersionKey key = new AppVersionKey(applicationToken, profileDto.getClientProfileVersion()); + AppVersionKey key = new AppVersionKey( + applicationToken, profileDto.getClientProfileVersion()); BaseSchemaInfo schemaInfo = clientProfileSchemas.get(key); if (schemaInfo == null) { EndpointProfileSchemaDto profileSchema = cacheService.getProfileSchemaByAppAndVersion(key); @@ -180,26 +189,33 @@ private void fetchSchemas(LogEventPackMessage message) { schemaInfo = new BaseSchemaInfo(ctlSchemaDto.getId(), schema); clientProfileSchemas.put(key, schemaInfo); } - logPack.setClientProfile(new BaseProfileInfo(schemaInfo, profileDto.getClientProfileBody())); + logPack.setClientProfile( + new BaseProfileInfo(schemaInfo, profileDto.getClientProfileBody())); } ProfileInfo serverProfile = logPack.getServerProfile(); if (serverProfile == null) { - AppVersionKey key = new AppVersionKey(applicationToken, profileDto.getServerProfileVersion()); + AppVersionKey key = new AppVersionKey( + applicationToken, profileDto.getServerProfileVersion()); BaseSchemaInfo schemaInfo = serverProfileSchemas.get(key); if (schemaInfo == null) { - ServerProfileSchemaDto serverProfileSchema = cacheService.getServerProfileSchemaByAppAndVersion(key); - CTLSchemaDto ctlSchemaDto = cacheService.getCtlSchemaById(serverProfileSchema.getCtlSchemaId()); + ServerProfileSchemaDto serverProfileSchema = + cacheService.getServerProfileSchemaByAppAndVersion(key); + CTLSchemaDto ctlSchemaDto = cacheService.getCtlSchemaById( + serverProfileSchema.getCtlSchemaId()); String schema = ctlService.flatExportAsString(ctlSchemaDto); schemaInfo = new BaseSchemaInfo(ctlSchemaDto.getId(), schema); serverProfileSchemas.put(key, schemaInfo); } - logPack.setServerProfile(new BaseProfileInfo(schemaInfo, profileDto.getServerProfileBody())); + logPack.setServerProfile( + new BaseProfileInfo(schemaInfo, profileDto.getServerProfileBody())); } } - protected void sendErrorMessageToEndpoint(LogEventPackMessage message, LogDeliveryErrorCode errorCode) { + protected void sendErrorMessageToEndpoint(LogEventPackMessage message, + LogDeliveryErrorCode errorCode) { if (message.getOriginator() != null) { - message.getOriginator().tell(new LogDeliveryMessage(message.getRequestId(), false, errorCode), ActorRef.noSender()); + message.getOriginator().tell(new LogDeliveryMessage( + message.getRequestId(), false, errorCode), ActorRef.noSender()); } else { LOG.warn("[{}] Can't send error message to unknown originator.", applicationToken); } @@ -220,36 +236,43 @@ protected void processLogAppenderNotification(Notification notification) { addLogAppender(appenderId); break; default: - LOG.debug("[{}][{}] Operation [{}] is not supported.", applicationToken, appenderId, notification.getOp()); + LOG.debug("[{}][{}] Operation [{}] is not supported.", + applicationToken, appenderId, notification.getOp()); } } protected void stop() { for (LogAppender logAppender : logAppenders.values()) { - LOG.info("[{}] Closing appender [{}] with name {}", applicationToken, logAppender.getAppenderId(), logAppender.getName()); + LOG.info("[{}] Closing appender [{}] with name {}", + applicationToken, logAppender.getAppenderId(), logAppender.getName()); logAppender.close(); } } private void addLogAppender(String appenderId) { - LOG.info("[{}] Adding log appender with id [{}].", applicationId, appenderId); + LOG.info("[{}] Adding log appender with id [{}].", + applicationId, appenderId); if (!logAppenders.containsKey(appenderId)) { LogAppender logAppender = logAppenderService.getApplicationAppender(appenderId); if (logAppender != null) { addAppender(appenderId, logAppender); - LOG.info("[{}] Log appender [{}] registered.", applicationId, appenderId); + LOG.info("[{}] Log appender [{}] registered.", + applicationId, appenderId); } } else { - LOG.info("[{}] Log appender [{}] is already registered.", applicationId, appenderId); + LOG.info("[{}] Log appender [{}] is already registered.", + applicationId, appenderId); } } private void removeLogAppender(String appenderId) { if (logAppenders.containsKey(appenderId)) { - LOG.info("[{}] Closing log appender with id [{}].", applicationToken, appenderId); + LOG.info("[{}] Closing log appender with id [{}].", + applicationToken, appenderId); removeAppender(appenderId).close(); } else { - LOG.warn("[{}] Can't remove unregistered appender with id [{}]", applicationToken, appenderId); + LOG.warn("[{}] Can't remove unregistered appender with id [{}]", + applicationToken, appenderId); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/TopicActor.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/TopicActor.java index 578fdf869e..c90222ef4b 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/TopicActor.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/TopicActor.java @@ -90,16 +90,20 @@ public TopicActor(NotificationDeltaService notificationService) { * @param calendar the calendar * @return the list */ - public static List filterMap(SortedMap pendingNotificationMap, int systemNfSchemaVersion, - int userNfSchemaVersion, Calendar calendar) { + public static List filterMap( + SortedMap pendingNotificationMap, + int systemNfSchemaVersion, + int userNfSchemaVersion, + Calendar calendar) { List pendingNotifications = new ArrayList<>(pendingNotificationMap.size()); long now = calendar.getTimeInMillis(); List expiredNotifications = null; for (NotificationDto dto : pendingNotificationMap.values()) { - LOG.trace("Filtering notification {} using system schema version {} and user schema version {}", dto, systemNfSchemaVersion, - userNfSchemaVersion); + LOG.trace("Filtering notification {} using system schema version " + + "{} and user schema version {}", + dto, systemNfSchemaVersion, userNfSchemaVersion); Date date = dto.getExpiredAt(); if (date != null && date.getTime() > now) { if (isSchemaVersionMatch(dto, systemNfSchemaVersion, userNfSchemaVersion)) { @@ -110,12 +114,14 @@ public static List filterMap(SortedMap(); } expiredNotifications.add(dto); - LOG.trace("Detected expired notification: {}, nfTime: {}, curTime: {}", dto, date == null ? date : date.getTime(), now); + LOG.trace("Detected expired notification: {}, nfTime: {}, curTime: {}", + dto, date == null ? date : date.getTime(), now); } } if (expiredNotifications != null) { - LOG.trace("Removing {} notifications from pendingNotificationMap", expiredNotifications.size()); + LOG.trace("Removing {} notifications from pendingNotificationMap", + expiredNotifications.size()); pendingNotificationMap.values().removeAll(expiredNotifications); } return pendingNotifications; @@ -129,7 +135,9 @@ public static List filterMap(SortedMap pendingNotificationMap = notificationCache.tailMap(seqNum, false); + SortedMap pendingNotificationMap = notificationCache.tailMap( + seqNum, false); Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("UTC")); - List pendingNotifications = filterMap(pendingNotificationMap, message.getSystemNfSchemaVersion(), + List pendingNotifications = filterMap( + pendingNotificationMap, message.getSystemNfSchemaVersion(), message.getUserNfSchemaVersion(), calendar); if (!pendingNotifications.isEmpty()) { LOG.debug("Detected new messages during endpoint subscription!"); - NotificationMessage notificationMessage = NotificationMessage.fromNotifications(pendingNotifications); + NotificationMessage notificationMessage = NotificationMessage.fromNotifications( + pendingNotifications); endpointActor.tell(notificationMessage, self()); } else { LOG.debug("No new messages detected. Subscribing endpoint actor to topic actor"); String endpointKey = message.getOriginator().path().name(); - ActorInfo actorInfo = new ActorInfo(endpointActor, message.getSystemNfSchemaVersion(), message.getUserNfSchemaVersion()); + ActorInfo actorInfo = new ActorInfo( + endpointActor, message.getSystemNfSchemaVersion(), message.getUserNfSchemaVersion()); if (endpointSessions.put(endpointKey, actorInfo) != null) { LOG.warn("Detected duplication of registration message: {}", message); } @@ -208,10 +220,13 @@ private void broadcastToAllEndpoints(ThriftNotificationMessage message) { LOG.warn("Can't find notification by id {}. Probably it has already expired!"); } else { notificationCache.put(notificationDto.getSecNum(), notificationDto); - LOG.debug("[{}] Put notification to topic actor cache {}", notificationDto.getTopicId(), notificationDto); - NotificationMessage notificationMessage = NotificationMessage.fromNotifications(Collections.singletonList(notificationDto)); + LOG.debug("[{}] Put notification to topic actor cache {}", + notificationDto.getTopicId(), notificationDto); + NotificationMessage notificationMessage = NotificationMessage.fromNotifications( + Collections.singletonList(notificationDto)); for (ActorInfo endpoint : endpointSessions.values()) { - if (isSchemaVersionMatch(notificationDto, endpoint.getSystemNfVersion(), endpoint.getUserNfVersion())) { + if (isSchemaVersionMatch( + notificationDto, endpoint.getSystemNfVersion(), endpoint.getUserNfVersion())) { endpoint.getActorRef().tell(notificationMessage, self()); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/endpoint/local/LocalEndpointActorMessageProcessor.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/endpoint/local/LocalEndpointActorMessageProcessor.java index f01a9f25bc..264d75a7e3 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/endpoint/local/LocalEndpointActorMessageProcessor.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/endpoint/local/LocalEndpointActorMessageProcessor.java @@ -521,7 +521,7 @@ private EndpointProfileDataDto convert(EndpointProfileDto profileDto) { } private void sendConnectToNewUser(ActorContext context, EndpointProfileDto endpointProfile) { - List ecfVersions = EntityConvertUtils.convertToECFVersions( + List ecfVersions = EntityConvertUtils.convertToEcfVersions( endpointProfile.getEcfVersionStates()); EndpointUserConnectMessage userRegistrationMessage = new EndpointUserConnectMessage( state.getUserId(), key, ecfVersions, diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/user/LocalUserActorMessageProcessor.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/user/LocalUserActorMessageProcessor.java index bda72aceb2..f7e68d23c3 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/user/LocalUserActorMessageProcessor.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/core/user/LocalUserActorMessageProcessor.java @@ -38,7 +38,7 @@ import org.kaaproject.kaa.server.operations.service.akka.messages.core.user.UserRouteInfoMessage; import org.kaaproject.kaa.server.operations.service.cache.CacheService; import org.kaaproject.kaa.server.operations.service.cache.EventClassFqnKey; -import org.kaaproject.kaa.server.operations.service.event.EndpointECFVersionMap; +import org.kaaproject.kaa.server.operations.service.event.EndpointEcfVersionMap; import org.kaaproject.kaa.server.operations.service.event.EndpointEvent; import org.kaaproject.kaa.server.operations.service.event.EventClassFamilyVersion; import org.kaaproject.kaa.server.operations.service.event.EventClassFqnVersion; @@ -83,7 +83,7 @@ public class LocalUserActorMessageProcessor { private final RouteTable routeTable; - private final EndpointECFVersionMap versionMap; + private final EndpointEcfVersionMap versionMap; private final EventStorage eventStorage; @@ -105,7 +105,7 @@ public class LocalUserActorMessageProcessor { this.tenantId = tenantId; this.endpoints = new HashMap<>(); this.routeTable = new RouteTable(); - this.versionMap = new EndpointECFVersionMap(); + this.versionMap = new EndpointEcfVersionMap(); this.eventStorage = new EventStorage(); this.eventDeliveryTable = new EventDeliveryTable(); this.localRoutes = new HashMap(); @@ -371,7 +371,7 @@ protected void sendEventToLocal(ActorContext context, EndpointEventReceiveMessag } private void processEvent(ActorContext context, EndpointEvent event) { - String fqn = event.getEventClassFQN(); + String fqn = event.getEventClassFqn(); LOG.debug("[{}] Processing event {} from {}", userId, event.getId(), event.getSender()); Integer version; diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/utils/EntityConvertUtils.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/utils/EntityConvertUtils.java index 14cbfcf48a..97c12c897d 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/utils/EntityConvertUtils.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/utils/EntityConvertUtils.java @@ -41,19 +41,25 @@ public static LogServerSync convert(Map responseMap List statusList = new ArrayList<>(); for (Entry response : responseMap.entrySet()) { LogDeliveryMessage message = response.getValue(); - statusList.add(new LogDeliveryStatus(response.getKey(), message.isSuccess() ? SyncStatus.SUCCESS : SyncStatus.FAILURE, - EntityConvertUtils.toErrorCode(message.getErrorCode()))); + statusList.add( + new LogDeliveryStatus(response.getKey(), message.isSuccess() + ? SyncStatus.SUCCESS + : SyncStatus.FAILURE, + EntityConvertUtils.toErrorCode(message.getErrorCode()))); } return new LogServerSync(statusList); } public static UserAttachResponse convert(UserVerificationResponseMessage value) { - UserAttachResponse response = new UserAttachResponse(value.isSuccess() ? SyncStatus.SUCCESS : SyncStatus.FAILURE, + UserAttachResponse response = new UserAttachResponse(value.isSuccess() + ? SyncStatus.SUCCESS + : SyncStatus.FAILURE, EntityConvertUtils.toErrorCode(value.getErrorCode()), value.getFailureReason()); return response; } - public static UserVerifierErrorCode toErrorCode(org.kaaproject.kaa.server.common.verifier.UserVerifierErrorCode errorCode) { + public static UserVerifierErrorCode toErrorCode( + org.kaaproject.kaa.server.common.verifier.UserVerifierErrorCode errorCode) { if (errorCode == null) { return null; } @@ -75,7 +81,8 @@ public static UserVerifierErrorCode toErrorCode(org.kaaproject.kaa.server.common } } - public static LogDeliveryErrorCode toErrorCode(org.kaaproject.kaa.server.common.log.shared.appender.LogDeliveryErrorCode errorCode) { + public static LogDeliveryErrorCode toErrorCode( + org.kaaproject.kaa.server.common.log.shared.appender.LogDeliveryErrorCode errorCode) { if (errorCode == null) { return null; } @@ -93,7 +100,8 @@ public static LogDeliveryErrorCode toErrorCode(org.kaaproject.kaa.server.common. } } - public static List convertToECFVersions(List ecfVersionStates) { + public static List convertToEcfVersions( + List ecfVersionStates) { List result = new ArrayList<>(ecfVersionStates.size()); for (EventClassFamilyVersionStateDto dto : ecfVersionStates) { result.add(new EventClassFamilyVersion(dto.getEcfId(), dto.getVersion())); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/AppProfileVersionsKey.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/AppProfileVersionsKey.java index d9c6017d22..6e91bd49f9 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/AppProfileVersionsKey.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/AppProfileVersionsKey.java @@ -54,7 +54,9 @@ public final class AppProfileVersionsKey implements Serializable { * @param endpointProfileSchemaVersion the endpoint profile schema version * @param serverProfileSchemaVersion the server profile schema version */ - public AppProfileVersionsKey(String applicationToken, Integer endpointProfileSchemaVersion, Integer serverProfileSchemaVersion) { + public AppProfileVersionsKey(String applicationToken, + Integer endpointProfileSchemaVersion, + Integer serverProfileSchemaVersion) { super(); this.applicationToken = applicationToken; this.endpointProfileSchemaVersion = endpointProfileSchemaVersion; @@ -77,9 +79,12 @@ public Integer getServerProfileSchemaVersion() { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result + ((applicationToken == null) ? 0 : applicationToken.hashCode()); - result = prime * result + ((endpointProfileSchemaVersion == null) ? 0 : endpointProfileSchemaVersion.hashCode()); - result = prime * result + ((serverProfileSchemaVersion == null) ? 0 : serverProfileSchemaVersion.hashCode()); + result = prime * result + + ((applicationToken == null) ? 0 : applicationToken.hashCode()); + result = prime * result + + ((endpointProfileSchemaVersion == null) ? 0 : endpointProfileSchemaVersion.hashCode()); + result = prime * result + + ((serverProfileSchemaVersion == null) ? 0 : serverProfileSchemaVersion.hashCode()); return result; } @@ -121,8 +126,9 @@ public boolean equals(Object obj) { @Override public String toString() { - return "AppProfileVersionsKey [applicationToken=" + applicationToken + ", endpointProfileSchemaVersion=" - + endpointProfileSchemaVersion + ", serverProfileSchemaVersion=" + serverProfileSchemaVersion + "]"; + return "AppProfileVersionsKey [applicationToken=" + applicationToken + + ", endpointProfileSchemaVersion=" + endpointProfileSchemaVersion + + ", serverProfileSchemaVersion=" + serverProfileSchemaVersion + "]"; } } \ No newline at end of file diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/AppSeqNumber.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/AppSeqNumber.java index 74266897d4..19e93fcd73 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/AppSeqNumber.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/AppSeqNumber.java @@ -20,9 +20,6 @@ public final class AppSeqNumber implements Serializable { - /** - * - */ private static final long serialVersionUID = -5524478984530847211L; private final String tenantId; diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/CacheService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/CacheService.java index 93bf3bea92..19fedc571f 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/CacheService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/CacheService.java @@ -161,7 +161,9 @@ public interface CacheService { * @param worker the worker * @return the merged configuration */ - Pair getMergedConfiguration(List egsList, Computable, Pair> worker); + Pair getMergedConfiguration(List egsList, + Computable, + Pair> worker); /** * Sets the merged configuration. @@ -180,7 +182,9 @@ public interface CacheService { * @return the delta * @throws GetDeltaException the get delta exception */ - ConfigurationCacheEntry getDelta(DeltaCacheKey deltaKey, Computable worker) throws GetDeltaException; + ConfigurationCacheEntry getDelta(DeltaCacheKey deltaKey, + Computable worker) throws GetDeltaException; /** * Sets the delta. @@ -200,7 +204,7 @@ public interface CacheService { PublicKey getEndpointKey(EndpointObjectHash hash); /** - * Gets the EndpointClassFamily Id using tenant Id and name; + * Gets the EndpointClassFamily Id using tenant Id and name. * * @param key the event class family id key * @return the EndpointClassFamily Id @@ -208,7 +212,7 @@ public interface CacheService { String getEventClassFamilyIdByName(EventClassFamilyIdKey key); /** - * Gets the Tenant Id by application token; + * Gets the Tenant Id by application token. * * @param appToken token of Application that belongs to Tenant * @return the Tenant Id @@ -216,7 +220,7 @@ public interface CacheService { String getTenantIdByAppToken(String appToken); /** - * Gets the {@link ApplicationDto} by application token; + * Gets the {@link ApplicationDto} by application token. * * @param appToken token of Application * @return the Application @@ -224,7 +228,7 @@ public interface CacheService { String getApplicationIdByAppToken(String appToken); /** - * Gets the application token by the sdk token + * Gets the application token by the sdk token. * * @param sdkToken the sdk token * @return application token for the specified sdk token @@ -232,7 +236,7 @@ public interface CacheService { String getAppTokenBySdkToken(String sdkToken); /** - * Gets the Event Class Family Id by Event Class FQN + * Gets the Event Class Family Id by Event Class FQN. * * @param fqn of one of the events that belong to target Event Class Family * @return the Event Class Family Id @@ -241,7 +245,7 @@ public interface CacheService { /** * Gets all possible Event Class Family - Application keys that are interested in receiving - * events for this particular Event Class + * events for this particular Event Class. * * @param eventClassVersion Event Class Id and Version pair * @return set of Event Class Family - Application keys @@ -258,7 +262,7 @@ public interface CacheService { PublicKey putEndpointKey(EndpointObjectHash hash, PublicKey endpointKey); /** - * Remove key from hash + * Remove key from hash. * * @param hash the hash * @param endpointKey the endpoint key @@ -301,7 +305,7 @@ public interface CacheService { void setEndpointService(EndpointService endpointService); /** - * Setter for test purposes only + * Setter for test purposes only. * * @param sdkProfileService the new sdk profile service */ @@ -387,13 +391,14 @@ public interface CacheService { String putConfId(ConfigurationIdKey key, String value); /** - * Put application event family maps + * Put application event family maps. * * @param key list of event family maps ids * @param value list of event family maps * @return the list */ - public List putApplicationEventFamilyMaps(List key, List value); + List putApplicationEventFamilyMaps( + List key, List value); void setEventClassService(EventClassService eventClassService); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/ConfigurationIdKey.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/ConfigurationIdKey.java index 0f6e7a727c..aee34d935a 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/ConfigurationIdKey.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/ConfigurationIdKey.java @@ -62,7 +62,9 @@ public final class ConfigurationIdKey implements Serializable { * @param applicationSeqNumber the application seq number * @param configSchemaVersion the config schema version */ - public ConfigurationIdKey(String applicationId, int applicationSeqNumber, int configSchemaVersion) { + public ConfigurationIdKey(String applicationId, + int applicationSeqNumber, + int configSchemaVersion) { this(applicationId, applicationSeqNumber, configSchemaVersion, null); } @@ -74,7 +76,9 @@ public ConfigurationIdKey(String applicationId, int applicationSeqNumber, int co * @param configSchemaVersion the config schema version * @param endpointGroupId the endpoint group id */ - public ConfigurationIdKey(String applicationToken, int applicationSeqNumber, int configSchemaVersion, + public ConfigurationIdKey(String applicationToken, + int applicationSeqNumber, + int configSchemaVersion, String endpointGroupId) { super(); this.applicationToken = applicationToken; @@ -116,8 +120,10 @@ public String getEndpointGroupId() { * @param endpointGroupId the new endpoint group id * @return the configuration id key */ - public ConfigurationIdKey copyWithNewEGId(String endpointGroupId) { - return new ConfigurationIdKey(this.applicationToken, this.applicationSeqNumber, this.configSchemaVersion, endpointGroupId); + public ConfigurationIdKey copyWithNewEgId(String endpointGroupId) { + return new ConfigurationIdKey( + this.applicationToken, this.applicationSeqNumber, + this.configSchemaVersion, endpointGroupId); } /* (non-Javadoc) diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/DeltaCacheKey.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/DeltaCacheKey.java index 2a2d542751..98a457a7cb 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/DeltaCacheKey.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/DeltaCacheKey.java @@ -47,18 +47,28 @@ public final class DeltaCacheKey implements Serializable { private final EndpointObjectHash userConfHash; - public DeltaCacheKey(AppVersionKey appConfigVersionKey, List endpointGroups, EndpointObjectHash userConfHash, + public DeltaCacheKey(AppVersionKey appConfigVersionKey, + List endpointGroups, + EndpointObjectHash userConfHash, EndpointObjectHash endpointConfHash) { this(appConfigVersionKey, endpointGroups, userConfHash, endpointConfHash, true, false); } - public DeltaCacheKey(AppVersionKey appConfigVersionKey, List endpointGroups, EndpointObjectHash userConfHash, - EndpointObjectHash endpointConfHash, boolean useConfigurationRawSchema) { - this(appConfigVersionKey, endpointGroups, userConfHash, endpointConfHash, useConfigurationRawSchema, false); + public DeltaCacheKey(AppVersionKey appConfigVersionKey, + List endpointGroups, + EndpointObjectHash userConfHash, + EndpointObjectHash endpointConfHash, + boolean useConfigurationRawSchema) { + this(appConfigVersionKey, endpointGroups, userConfHash, + endpointConfHash, useConfigurationRawSchema, false); } - public DeltaCacheKey(AppVersionKey appConfigVersionKey, List endpointGroups, - EndpointObjectHash userConfHash, EndpointObjectHash endpointConfHash, boolean useConfigurationRawSchema, boolean resyncOnly) { + public DeltaCacheKey(AppVersionKey appConfigVersionKey, + List endpointGroups, + EndpointObjectHash userConfHash, + EndpointObjectHash endpointConfHash, + boolean useConfigurationRawSchema, + boolean resyncOnly) { this.appConfigVersionKey = appConfigVersionKey; this.userConfHash = userConfHash; this.endpointGroups = endpointGroups; @@ -102,21 +112,45 @@ public EndpointObjectHash getUserConfHash() { } @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object obj) { + if (this == obj) { + return true; + } - DeltaCacheKey that = (DeltaCacheKey) o; + if (obj == null || getClass() != obj.getClass()) { + return false; + } + + DeltaCacheKey that = (DeltaCacheKey) obj; + + if (resyncOnly != that.resyncOnly) { + return false; + } - if (resyncOnly != that.resyncOnly) return false; - if (useConfigurationRawSchema != that.useConfigurationRawSchema) return false; - if (appConfigVersionKey != null ? !appConfigVersionKey.equals(that.appConfigVersionKey) : that.appConfigVersionKey != null) + if (useConfigurationRawSchema != that.useConfigurationRawSchema) { return false; - if (endpointGroups != null ? !endpointGroups.equals(that.endpointGroups) : that.endpointGroups != null) + } + + if (appConfigVersionKey != null + ? !appConfigVersionKey.equals(that.appConfigVersionKey) + : that.appConfigVersionKey != null) { + return false; + } + + if (endpointGroups != null + ? !endpointGroups.equals(that.endpointGroups) + : that.endpointGroups != null) { return false; - if (endpointConfHash != null ? !endpointConfHash.equals(that.endpointConfHash) : that.endpointConfHash != null) + } + + if (endpointConfHash != null + ? !endpointConfHash.equals(that.endpointConfHash) + : that.endpointConfHash != null) { return false; - return userConfHash != null ? userConfHash.equals(that.userConfHash) : that.userConfHash == null; + } + return userConfHash != null + ? userConfHash.equals(that.userConfHash) + : that.userConfHash == null; } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/EventClassFqnKey.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/EventClassFqnKey.java index df4196bbb7..24cd62084f 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/EventClassFqnKey.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/EventClassFqnKey.java @@ -20,9 +20,6 @@ public final class EventClassFqnKey implements Serializable { - /** - * - */ private static final long serialVersionUID = 4837917862920568450L; private final String tenantId; diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/TopicListCacheEntry.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/TopicListCacheEntry.java index fb885e0a4c..fd4e189016 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/TopicListCacheEntry.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/TopicListCacheEntry.java @@ -61,26 +61,31 @@ public int hashCode() { @Override public boolean equals(Object obj) { - if (this == obj) + if (this == obj) { return true; - if (obj == null) + } + + if (obj == null) { return false; - if (getClass() != obj.getClass()) + } + + if (getClass() != obj.getClass()) { return false; + } + TopicListCacheEntry other = (TopicListCacheEntry) obj; - if (hash == null) { - if (other.hash != null) + if (hash == null && other.hash != null) { return false; - } else if (!hash.equals(other.hash)) - return false; - if (simpleHash != other.simpleHash) + } else if (!hash.equals(other.hash)) { return false; - return true; + } + return simpleHash == other.simpleHash; } @Override public String toString() { - return "TopicListCacheEntry [simpleHash=" + simpleHash + ", hash=" + hash + ", topics=" + topics + "]"; + return "TopicListCacheEntry [simpleHash=" + simpleHash + ", hash=" + + hash + ", topics=" + topics + "]"; } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/concurrent/CacheTemporaryMemorizer.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/concurrent/CacheTemporaryMemorizer.java index 5ee340b42b..51c368fda9 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/concurrent/CacheTemporaryMemorizer.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/concurrent/CacheTemporaryMemorizer.java @@ -52,16 +52,16 @@ public class CacheTemporaryMemorizer { * If the Throwable is an Error, throw it; if it is a RuntimeException * return it, otherwise throw IllegalStateException. * - * @param t the t + * @param throwable the t * @return the runtime exception */ - public static RuntimeException launderThrowable(Throwable t) { - if (t instanceof RuntimeException) { - return (RuntimeException) t; - } else if (t instanceof Error) { - throw (Error) t; + public static RuntimeException launderThrowable(Throwable throwable) { + if (throwable instanceof RuntimeException) { + return (RuntimeException) throwable; + } else if (throwable instanceof Error) { + throw (Error) throwable; } else { - throw new IllegalStateException("Cache Operation Exception", t); + throw new IllegalStateException("Cache Operation Exception", throwable); } } @@ -77,37 +77,38 @@ public V compute(final K key, final Computable worker) { throw new InvalidParameterException("Cache key can't be null"); } while (true) { - Future f = cache.get(key); - if (f == null) { + Future future = cache.get(key); + if (future == null) { Callable eval = new Callable() { public V call() throws InterruptedException { return worker.compute(key); } }; FutureTask ft = new FutureTask(eval); - f = cache.putIfAbsent(key, ft); - if (f == null) { - f = ft; + future = cache.putIfAbsent(key, ft); + if (future == null) { + future = ft; try { ft.run(); //the idea is not to cache permanently but only for the time of execution. - //thus, technically, if time of calculation >> time of external cache put -> we will run calculation maximum 2 times. - } catch (Throwable e) { - LOG.error("Exception catched: ", e); - throw e; + //thus, technically, if time of calculation >> time of external + // cache put -> we will run calculation maximum 2 times. + } catch (Throwable ex) { + LOG.error("Exception catched: ", ex); + throw ex; } finally { cache.remove(key, ft); } } } try { - return f.get(); - } catch (CancellationException e) { - LOG.error("Exception catched: ", e); - cache.remove(key, f); - } catch (ExecutionException | InterruptedException e) { - LOG.error("Exception catched: ", e); - throw launderThrowable(e); + return future.get(); + } catch (CancellationException ex) { + LOG.error("Exception catched: ", ex); + cache.remove(key, future); + } catch (ExecutionException | InterruptedException ex) { + LOG.error("Exception catched: ", ex); + throw launderThrowable(ex); } } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/DefaultEventService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/DefaultEventService.java index 4567e80f7b..f97ea77834 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/DefaultEventService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/DefaultEventService.java @@ -429,7 +429,7 @@ public void setResolver(OperationsServerResolver resolver) { } /** - * Repack list of EventRoute messages to list of EventMessage + * Repack list of EventRoute messages to list of EventMessage. * * @param routes List * @return List @@ -444,7 +444,7 @@ private List packMessage(List routes) { } /** - * Pack UserRouteInfo into list of EventMessage + * Pack UserRouteInfo into list of EventMessage. * * @param userRoute UserRouteInfo * @return List @@ -455,7 +455,7 @@ private List packMessage(UserRouteInfo userRoute) { } /** - * Pack Event into list of EventMessage + * Pack Event into list of EventMessage. * * @param event Event * @return List @@ -477,7 +477,7 @@ protected void notifyListenersOnServerProblem(String id) { } /** - * Transform Collection into List + * Transform Collection into List. * * @param routeInfos Collection * @return List diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointECFVersionMap.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointEcfVersionMap.java similarity index 95% rename from server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointECFVersionMap.java rename to server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointEcfVersionMap.java index dd0d86a48e..6cdb20a244 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointECFVersionMap.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointEcfVersionMap.java @@ -22,11 +22,11 @@ import java.util.List; import java.util.Map; -public class EndpointECFVersionMap { +public class EndpointEcfVersionMap { private final Map> map; - public EndpointECFVersionMap() { + public EndpointEcfVersionMap() { super(); map = new HashMap>(); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointEvent.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointEvent.java index 0f3ab12cb7..95d1c24573 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointEvent.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EndpointEvent.java @@ -58,7 +58,7 @@ public Event getEvent() { return event; } - public String getEventClassFQN() { + public String getEventClassFqn() { return event.getEventClassFqn(); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventService.java index d4631ab0fa..57a9434576 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventService.java @@ -72,7 +72,8 @@ public interface EventService { * * @param routeInfo UserRouteInfo */ - void sendUserRouteInfo(org.kaaproject.kaa.server.operations.service.event.UserRouteInfo routeInfo); + void sendUserRouteInfo( + org.kaaproject.kaa.server.operations.service.event.UserRouteInfo routeInfo); /** * Register event route engine listener, used to inform route engine on @@ -83,7 +84,7 @@ public interface EventService { void addListener(EventServiceListener listener); /** - * Deregister event route engine listener + * Deregister event route engine listener. * * @param listener EventServiceListener */ @@ -91,7 +92,7 @@ public interface EventService { /** * Operations Server thrift interface, used to receive unified event message - * which includes RouteInfo,UserRouteInfo and Event messages + * which includes RouteInfo,UserRouteInfo and Event messages. * * @param messages List of type EventMessage */ @@ -112,14 +113,14 @@ public interface EventService { void setResolver(OperationsServerResolver resolver); /** - * Sends routing information about endpoint to global user actor + * Sends routing information about endpoint to global user actor. * * @param route the route */ void sendEndpointRouteInfo(GlobalRouteInfo route); /** - * Sends configuration update information to specific endpoint actor; + * Sends configuration update information to specific endpoint actor. * * @param serverId the server id * @param update the update @@ -127,7 +128,7 @@ public interface EventService { void sendEndpointStateInfo(String serverId, EndpointUserConfigurationUpdate update); /** - * Checks if global user actor for specified user is located on current node + * Checks if global user actor for specified user is located on current node. * * @param userId to check * @return true if global user actor is located on this node, false otherwise. diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventServiceListener.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventServiceListener.java index f6d31e63b6..91d1ef17d8 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventServiceListener.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventServiceListener.java @@ -29,14 +29,14 @@ public interface EventServiceListener { void onServerError(String serverId); /** - * Reports information about endpoint to global user actor + * Reports information about endpoint to global user actor. * * @param update - information about endpoint activity */ void onEndpointRouteUpdate(GlobalRouteInfo update); /** - * Reports update of user configuration to the endpoint user actor + * Reports update of user configuration to the endpoint user actor. * * @param update - endpoint user configuration update */ diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventStorage.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventStorage.java index 0221abe2e0..c5649f4c4b 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventStorage.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventStorage.java @@ -46,6 +46,13 @@ public List getEvents(RouteTableKey key) { return getEvents(key, null); } + /** + * Returns endpoint events. + * + * @param key route table key + * @param targetAddress route table address + * @return endpoint events + */ public List getEvents(RouteTableKey key, RouteTableAddress targetAddress) { String target = null; if (targetAddress != null) { @@ -57,7 +64,8 @@ public List getEvents(RouteTableKey key, RouteTableAddress target if (targetAddress != null && targetAddress.getEndpointKey().equals(event.getSender())) { continue; } - if (entry.getValue().contains(key) && (event.getTarget() == null || target == null || event.getTarget().equals(target))) { + if (entry.getValue().contains(key) + && (event.getTarget() == null || target == null || event.getTarget().equals(target))) { result.add(entry.getKey()); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/GlobalRouteInfo.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/GlobalRouteInfo.java index 298776b4c8..09f8976f41 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/GlobalRouteInfo.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/GlobalRouteInfo.java @@ -28,14 +28,18 @@ public final class GlobalRouteInfo extends ClusterRouteInfo { private final int cfVersion; private final byte[] ucfHash; - private GlobalRouteInfo(String tenantId, String userId, RouteTableAddress address, int cfVersion, byte[] ucfHash, + private GlobalRouteInfo(String tenantId, String userId, + RouteTableAddress address, + int cfVersion, + byte[] ucfHash, RouteOperation routeOperation) { super(tenantId, userId, address, routeOperation); this.cfVersion = cfVersion; this.ucfHash = ucfHash; } - public static GlobalRouteInfo add(String tenantId, String userId, RouteTableAddress address, int cfVersion, byte[] ucfHash) { + public static GlobalRouteInfo add(String tenantId, String userId, RouteTableAddress address, + int cfVersion, byte[] ucfHash) { return new GlobalRouteInfo(tenantId, userId, address, cfVersion, ucfHash, RouteOperation.ADD); } @@ -44,11 +48,16 @@ public static GlobalRouteInfo delete(String tenantId, String userId, RouteTableA } public static GlobalRouteInfo fromThrift(EndpointRouteUpdate message) { - RouteTableAddress address = new RouteTableAddress(EndpointObjectHash.fromBytes(message.getRouteAddress().getEndpointKey()), message - .getRouteAddress().getApplicationToken(), message.getRouteAddress().getOperationsServerId()); - RouteOperation operation = message.getUpdateType() == EventRouteUpdateType.ADD ? RouteOperation.ADD : RouteOperation.DELETE; - return new GlobalRouteInfo(message.getTenantId(), message.getUserId(), address, message.getCfSchemaVersion(), message.getUcfHash(), - operation); + RouteTableAddress address = new RouteTableAddress( + EndpointObjectHash.fromBytes(message.getRouteAddress().getEndpointKey()), + message.getRouteAddress().getApplicationToken(), + message.getRouteAddress().getOperationsServerId()); + RouteOperation operation = message.getUpdateType() == EventRouteUpdateType.ADD + ? RouteOperation.ADD + : RouteOperation.DELETE; + return new GlobalRouteInfo + (message.getTenantId(), message.getUserId(), address, + message.getCfSchemaVersion(), message.getUcfHash(), operation); } public int getCfVersion() { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RemoteEndpointEvent.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RemoteEndpointEvent.java index c63d974cfb..4e99a720a7 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RemoteEndpointEvent.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RemoteEndpointEvent.java @@ -25,7 +25,18 @@ public final class RemoteEndpointEvent { private final EndpointEvent event; private final RouteTableAddress recipient; - public RemoteEndpointEvent(String tenantId, String userId, EndpointEvent event, RouteTableAddress recipient) { + /** + * All-args constructor. + * + * @param tenantId tenant identifier + * @param userId user identifier + * @param event endpoint event + * @param recipient recipient address + */ + public RemoteEndpointEvent(String tenantId, + String userId, + EndpointEvent event, + RouteTableAddress recipient) { super(); this.tenantId = tenantId; this.userId = userId; diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteInfo.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteInfo.java index cd191be29f..b479d1dea3 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteInfo.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteInfo.java @@ -24,16 +24,22 @@ public final class RouteInfo extends ClusterRouteInfo { private final List ecfVersions; - public RouteInfo(String tenantId, String userId, RouteTableAddress address, List ecfVersions) { + public RouteInfo(String tenantId, + String userId, + RouteTableAddress address, + List ecfVersions) { this(tenantId, userId, address, ecfVersions, RouteOperation.ADD); } - public RouteInfo(String tenantId, String userId, RouteTableAddress address, List ecfVersions, RouteOperation routeOperation) { + public RouteInfo(String tenantId, String userId, RouteTableAddress address, + List ecfVersions, RouteOperation routeOperation) { super(tenantId, userId, address, routeOperation); this.ecfVersions = ecfVersions; } - public static RouteInfo deleteRouteFromAddress(String tenantId, String userId, RouteTableAddress address) { + public static RouteInfo deleteRouteFromAddress(String tenantId, + String userId, + RouteTableAddress address) { return new RouteInfo(tenantId, userId, address, null, RouteOperation.DELETE); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTable.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTable.java index 734d545cd1..cfd3a5a14d 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTable.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTable.java @@ -35,6 +35,9 @@ public class RouteTable { private final Set remoteServersSet; private final Map> localAddressMap; + /** + * Instantiates new route table. + */ public RouteTable() { super(); routes = new HashMap>(); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTableAddress.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTableAddress.java index 60dea2a849..129aa1f2af 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTableAddress.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTableAddress.java @@ -27,7 +27,9 @@ public RouteTableAddress(EndpointObjectHash endpointKey, String applicationToken this(endpointKey, applicationToken, null); } - public RouteTableAddress(EndpointObjectHash endpointKey, String applicationToken, String serverId) { + public RouteTableAddress(EndpointObjectHash endpointKey, + String applicationToken, + String serverId) { super(); this.endpointKey = endpointKey; this.applicationToken = applicationToken; @@ -105,7 +107,9 @@ public boolean equals(Object obj) { */ @Override public String toString() { - return "RouteTableAddress [endpointKey=" + endpointKey + ", serverId=" + serverId + ", applicationToken=" + applicationToken + "]"; + return "RouteTableAddress [endpointKey=" + endpointKey + + ", serverId=" + serverId + ", applicationToken=" + + applicationToken + "]"; } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/history/DefaultHistoryDeltaService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/history/DefaultHistoryDeltaService.java index 66b72f1333..68e02ac200 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/history/DefaultHistoryDeltaService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/history/DefaultHistoryDeltaService.java @@ -92,12 +92,12 @@ public HistoryDelta getDelta(EndpointProfileDto profile, EndpointGroupStateDto groupAllState = new EndpointGroupStateDto(); groupAllState.setEndpointGroupId(groupDto.getId()); groupAllState.setConfigurationId(cacheService.getConfIdByKey( - confIdKey.copyWithNewEGId(groupDto.getId()))); + confIdKey.copyWithNewEgId(groupDto.getId()))); result.add(groupAllState); for (ProfileFilterDto filter : filters) { String confId = cacheService.getConfIdByKey( - confIdKey.copyWithNewEGId(filter.getEndpointGroupId())); + confIdKey.copyWithNewEgId(filter.getEndpointGroupId())); EndpointGroupStateDto endpointGroupState = new EndpointGroupStateDto(); endpointGroupState.setEndpointGroupId(filter.getEndpointGroupId()); endpointGroupState.setProfileFilterId(filter.getId()); @@ -226,7 +226,7 @@ public HistoryDelta getDelta(EndpointProfileDto profile, for (Entry entry : groupsMap.entrySet()) { if (entry.getValue().getConfigurationId() == null) { LOG.debug("[{}] Attempt to fetch configuration id for {}", endpointId, entry.getKey()); - String confId = cacheService.getConfIdByKey(confIdKey.copyWithNewEGId(entry.getKey())); + String confId = cacheService.getConfIdByKey(confIdKey.copyWithNewEgId(entry.getKey())); if (confId != null) { entry.getValue().setConfigurationId(confId); } else { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/metrics/DefaultMerticsService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/metrics/DefaultMerticsService.java index dbafc760e2..ff21606ba0 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/metrics/DefaultMerticsService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/metrics/DefaultMerticsService.java @@ -93,7 +93,8 @@ public void stopReport() { private void registerSystemMonitor() { LOG.info("Registering load average usage metrics."); - metrics.register(MetricRegistry.name(SystemMonitoringInfo.class, "system-load-average"), new Gauge() { + metrics.register(MetricRegistry.name( + SystemMonitoringInfo.class, "system-load-average"), new Gauge() { @Override public Double getValue() { return monitor.getLoadAverage(); @@ -101,7 +102,8 @@ public Double getValue() { }); LOG.info("Registering heap memory usage metrics."); - metrics.register(MetricRegistry.name(SystemMonitoringInfo.class, "heap-memory-usage.mb"), new Gauge() { + metrics.register(MetricRegistry.name( + SystemMonitoringInfo.class, "heap-memory-usage.mb"), new Gauge() { @Override public Long getValue() { return monitor.getHeapMemoryUsage(); @@ -109,7 +111,8 @@ public Long getValue() { }); LOG.info("Registering non heap memory usage metrics."); - metrics.register(MetricRegistry.name(SystemMonitoringInfo.class, "non-heap-memory-usage.mb"), new Gauge() { + metrics.register(MetricRegistry.name( + SystemMonitoringInfo.class, "non-heap-memory-usage.mb"), new Gauge() { @Override public Long getValue() { return monitor.getNonHeapMemoryUsage(); @@ -117,7 +120,8 @@ public Long getValue() { }); LOG.info("Registering live thread count metrics."); - metrics.register(MetricRegistry.name(SystemMonitoringInfo.class, "thread-count"), new Gauge() { + metrics.register(MetricRegistry.name( + SystemMonitoringInfo.class, "thread-count"), new Gauge() { @Override public Integer getValue() { return monitor.getLiveThreadCount(); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/notification/DefaultNotificationDeltaService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/notification/DefaultNotificationDeltaService.java index b47b277d93..92bf83df97 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/notification/DefaultNotificationDeltaService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/notification/DefaultNotificationDeltaService.java @@ -87,7 +87,9 @@ public class DefaultNotificationDeltaService implements NotificationDeltaService private EndpointService endpointService; @Override - public TopicListCacheEntry getTopicListHash(String appToken, String endpointId, EndpointProfileDto profile) { + public TopicListCacheEntry getTopicListHash(String appToken, + String endpointId, + EndpointProfileDto profile) { LOG.debug("[{}][{}] Calculating new topic list", appToken, endpointId); List topics = recalculateTopicList(profile.getGroupState()); Collections.sort(topics); @@ -99,7 +101,8 @@ public TopicListCacheEntry getTopicListHash(String appToken, String endpointId, joiner.add(id.toString()); } int simpleHash = Arrays.hashCode(ids); - EndpointObjectHash complexHash = EndpointObjectHash.fromBytes(Sha1HashUtils.hashToBytes(joiner.toString())); + EndpointObjectHash complexHash = EndpointObjectHash.fromBytes( + Sha1HashUtils.hashToBytes(joiner.toString())); TopicListCacheEntry entry = new TopicListCacheEntry(simpleHash, complexHash, topics); cacheService.putTopicList(complexHash, entry); LOG.debug("[{}][{}] Calculated new topic list {}", appToken, endpointId, entry); @@ -126,7 +129,8 @@ public GetNotificationResponse getNotificationDelta(GetNotificationRequest reque if (request.getTopicHash() != profile.getSimpleTopicHash()) { LOG.debug("[{}] Topic list changed. recalculating topic list", endpointId); - TopicListCacheEntry topicListCache = cacheService.getTopicListByHash(EndpointObjectHash.fromBytes(profile.getTopicHash())); + TopicListCacheEntry topicListCache = cacheService.getTopicListByHash( + EndpointObjectHash.fromBytes(profile.getTopicHash())); List topicList = topicListCache.getTopics(); LOG.debug("[{}] New topic list contains {} topics", endpointId, topicList.size()); List allPossibleTopics = new ArrayList<>(topicList.size()); @@ -136,7 +140,9 @@ public GetNotificationResponse getNotificationDelta(GetNotificationRequest reque if (topic.getType() == TopicTypeDto.MANDATORY) { if (subscriptionSet.add(topic.getId())) { // NOSONAR subscriptionSetChanged = true; - LOG.debug("[{}] added subscription for mandatory topic id: {}, name: {}", endpointId, topic.getId(), + LOG.debug("[{}] added subscription for mandatory topic id: {}, name: {}", + endpointId, + topic.getId(), topic.getName()); } } @@ -150,15 +156,17 @@ public GetNotificationResponse getNotificationDelta(GetNotificationRequest reque } if (request.getSubscriptionCommands() != null) { - for (SubscriptionCommand sCommand : request.getSubscriptionCommands()) { - if (sCommand.getCommand() == SubscriptionCommandType.ADD) { - if (subscriptionSet.add(sCommand.getTopicId())) { - LOG.debug("[{}] added subscription for topic id: {} based on client request", endpointId, sCommand.getTopicId()); + for (SubscriptionCommand subscriptionCommand : request.getSubscriptionCommands()) { + if (subscriptionCommand.getCommand() == SubscriptionCommandType.ADD) { + if (subscriptionSet.add(subscriptionCommand.getTopicId())) { + LOG.debug("[{}] added subscription for topic id: {} based on client request", + endpointId, subscriptionCommand.getTopicId()); subscriptionSetChanged = true; } } else { - if (subscriptionSet.remove(sCommand.getTopicId())) { - LOG.debug("[{}] removed subscription for topic id: {} based on client request", endpointId, sCommand.getTopicId()); + if (subscriptionSet.remove(subscriptionCommand.getTopicId())) { + LOG.debug("[{}] removed subscription for topic id: {} based on client request", + endpointId, subscriptionCommand.getTopicId()); subscriptionSetChanged = true; } } @@ -173,10 +181,13 @@ public GetNotificationResponse getNotificationDelta(GetNotificationRequest reque for (String topicId : subscriptionSet) { int seqNumber = subscriptionStates.get(topicId); LOG.debug( - "[{}] fetch new subscriptions for topic id: {}, system schema version {}, user schema version {}, starting seq number {}", - endpointId, topicId, profile.getSystemNfVersion(), profile.getUserNfVersion(), seqNumber); - List topicNotifications = notificationService.findNotificationsByTopicIdAndVersionAndStartSecNum(topicId, - seqNumber, profile.getSystemNfVersion(), profile.getUserNfVersion()); + "[{}] fetch new subscriptions for topic id: {}, system schema version {}, " + + "user schema version {}, starting seq number {}", + endpointId, topicId, profile.getSystemNfVersion(), + profile.getUserNfVersion(), seqNumber); + List topicNotifications = + notificationService.findNotificationsByTopicIdAndVersionAndStartSecNum( + topicId, seqNumber, profile.getSystemNfVersion(), profile.getUserNfVersion()); if (topicNotifications != null) { int count = 0; for (NotificationDto notification : topicNotifications) { @@ -187,7 +198,8 @@ public GetNotificationResponse getNotificationDelta(GetNotificationRequest reque count++; } } - LOG.debug("[{}] detected {} new subscriptions for topic id: {} ", endpointId, count, topicId); + LOG.debug("[{}] detected {} new subscriptions for topic id: {} ", + endpointId, count, topicId); subscriptionStates.put(topicId, seqNumber); } } @@ -195,20 +207,24 @@ public GetNotificationResponse getNotificationDelta(GetNotificationRequest reque if (request.getAcceptedUnicastNotifications() != null) { for (String acceptedUnicastId : request.getAcceptedUnicastNotifications()) { notificationService.removeUnicastNotificationById(acceptedUnicastId); - LOG.debug("[{}] deleted accepted unicast notification {} ", endpointId, acceptedUnicastId); + LOG.debug("[{}] deleted accepted unicast notification {} ", + endpointId, acceptedUnicastId); } } - List unicastNotifications = notificationService.findUnicastNotificationsByKeyHash(request.getProfile() - .getEndpointKeyHash()); + List unicastNotifications = + notificationService.findUnicastNotificationsByKeyHash( + request.getProfile().getEndpointKeyHash()); for (EndpointNotificationDto unicastNotification : unicastNotifications) { - LOG.debug("[{}] detected new unicast notification: {} ", endpointId, unicastNotification.getId()); + LOG.debug("[{}] detected new unicast notification: {} ", + endpointId, unicastNotification.getId()); LOG.trace("[{}] detected new unicast notification: {} ", endpointId, unicastNotification); NotificationDto notificationDto = unicastNotification.getNotificationDto(); if (notificationDto != null) { Date date = notificationDto.getExpiredAt(); if (date != null && date.getTime() > now) { - LOG.trace("[{}] notification expiration time is {}({}) which is later then {}", endpointId, date.getTime(), date, now); + LOG.trace("[{}] notification expiration time is {}({}) which is later then {}", + endpointId, date.getTime(), date, now); notificationDto.setId(unicastNotification.getId()); notifications.add(notificationDto); } @@ -219,7 +235,8 @@ public GetNotificationResponse getNotificationDelta(GetNotificationRequest reque response.setSubscriptionStates(subscriptionStates); if (subscriptionSetChanged) { - LOG.debug("[{}] Updating profile with subscription set. Size {}", endpointId, subscriptionSet.size()); + LOG.debug("[{}] Updating profile with subscription set. Size {}", + endpointId, subscriptionSet.size()); response.setSubscriptionSetChanged(true); response.setSubscriptionSet(subscriptionSet); } @@ -246,14 +263,15 @@ private NotificationDto convertUnicastNotification(EndpointNotificationDto unica * @param subscriptionSet the subscription set * @return the map */ - private Map buildTopicStateMap(GetNotificationRequest request, Set subscriptionSet) { - Map topicStates = new HashMap(); + private Map buildTopicStateMap(GetNotificationRequest request, + Set subscriptionSet) { + Map topicStates = new HashMap<>(); if (request.getTopicStates() != null) { for (TopicState topicState : request.getTopicStates()) { topicStates.put(topicState.getTopicId(), topicState.getSeqNumber()); } } - Map subscriptionStates = new HashMap(); + Map subscriptionStates = new HashMap<>(); for (String subscription : subscriptionSet) { Integer seqNumber = topicStates.get(subscription); subscriptionStates.put(subscription, seqNumber != null ? seqNumber : 0); @@ -265,7 +283,7 @@ private Map buildTopicStateMap(GetNotificationRequest request, /** * Recalculate topic list. * - * @param historyDelta the history delta + * @param groups endpoint group state list * @return the list */ private List recalculateTopicList(List groups) { @@ -279,7 +297,7 @@ private List recalculateTopicList(List groups) } } } - List topicList = new ArrayList(topicSet); + List topicList = new ArrayList<>(topicSet); Collections.sort(topicList, new Comparator() { @Override public int compare(TopicDto o1, TopicDto o2) { @@ -296,7 +314,9 @@ public int compare(TopicDto o1, TopicDto o2) { * @return the sets the */ private Set buildSubscriptionSet(EndpointProfileDto profile) { - return profile.getSubscriptions() != null ? new HashSet(profile.getSubscriptions()) : new HashSet(); + return profile.getSubscriptions() != null + ? new HashSet<>(profile.getSubscriptions()) + : new HashSet<>(); } /* @@ -318,7 +338,8 @@ public NotificationDto findNotificationById(String notificationId) { */ @Override public NotificationDto findUnicastNotificationById(String unicastNotificationId) { - EndpointNotificationDto notification = notificationService.findUnicastNotificationById(unicastNotificationId); + EndpointNotificationDto notification = notificationService.findUnicastNotificationById( + unicastNotificationId); if (notification == null) { return null; } else { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/notification/NotificationDeltaService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/notification/NotificationDeltaService.java index 47d6d60072..25309afa53 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/notification/NotificationDeltaService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/notification/NotificationDeltaService.java @@ -53,13 +53,15 @@ public interface NotificationDeltaService { NotificationDto findUnicastNotificationById(String unicastNotificationId); /** - * Calculate topic list hash for given profile + * Calculate topic list hash for given profile. * * @param appToken - application token * @param endpointId - endpoint id * @param profile - endpoint profile * @return topic list cache entry */ - TopicListCacheEntry getTopicListHash(String appToken, String endpointId, EndpointProfileDto profile); + TopicListCacheEntry getTopicListHash(String appToken, + String endpointId, + EndpointProfileDto profile); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/profile/DefaultProfileService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/profile/DefaultProfileService.java index c881b171db..92b2fc5a8f 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/profile/DefaultProfileService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/profile/DefaultProfileService.java @@ -76,20 +76,82 @@ public EndpointProfileDto getProfile(EndpointObjectHash endpointKey) { } @Override - public EndpointProfileDto updateProfile(EndpointProfileDto profile, - BiFunction mergeFunction) { + public EndpointProfileDto updateProfile( + EndpointProfileDto profile, + BiFunction mergeFunction) { return updateProfile(profile, mergeFunction, 3); } - private EndpointProfileDto updateProfile(EndpointProfileDto update, - BiFunction mergeFunction, int retryCount) { + /* + * (non-Javadoc) + * + * @see org.kaaproject.kaa.server.operations.service.profile.ProfileService# + * updateProfile + * (org.kaaproject.kaa.server.operations.pojo.UpdateProfileRequest) + */ + @Override + public EndpointProfileDto updateProfile(UpdateProfileRequest request) { + LOG.debug("Updating Profile for {}", request.getEndpointKeyHash()); + + EndpointProfileDto dto = endpointService.findEndpointProfileByKeyHash( + request.getEndpointKeyHash().getData()); + + AppSeqNumber appSeqNumber = cacheService.getAppSeqNumber(request.getApplicationToken()); + + SdkProfileDto sdkProfile = cacheService.getSdkProfileBySdkToken(request.getSdkToken()); + String profileJson = decodeProfile( + request.getProfile(), appSeqNumber.getAppToken(), sdkProfile.getProfileSchemaVersion()); + + Function updateFunction = profile -> { + if (request.getAccessToken() != null) { + profile.setAccessToken(request.getAccessToken()); + } + profile.setClientProfileBody(profileJson); + profile.setProfileHash(EndpointObjectHash.fromSha1(request.getProfile()).getData()); + + populateVersionStates(appSeqNumber.getTenantId(), profile, sdkProfile); + profile.setGroupState(new ArrayList<>()); + profile.setSequenceNumber(0); + return profile; + }; + return updateProfile(updateFunction.apply(dto), (storedProfile, newProfile) -> { + return updateFunction.apply(storedProfile); + }); + } + + @Override + public EndpointProfileDto updateProfile(ClientSyncMetaData metaData, + EndpointObjectHash keyHash, + boolean useConfigurationRawSchema) { + LOG.debug("Updating Profile for {}", keyHash); + EndpointProfileDto dto = endpointService.findEndpointProfileByKeyHash(keyHash.getData()); + AppSeqNumber appSeqNumber = cacheService.getAppSeqNumber(metaData.getApplicationToken()); + SdkProfileDto sdkProfile = cacheService.getSdkProfileBySdkToken(metaData.getSdkToken()); + + Function updateFunction = profile -> { + populateVersionStates(appSeqNumber.getTenantId(), profile, sdkProfile); + profile.setGroupState(new ArrayList<>()); + profile.setUseConfigurationRawSchema(useConfigurationRawSchema); + profile.setSequenceNumber(0); + return profile; + }; + return updateProfile(updateFunction.apply(dto), (storedProfile, newProfile) -> { + return updateFunction.apply(storedProfile); + }); + } + + private EndpointProfileDto updateProfile( + EndpointProfileDto update, + BiFunction mergeFunction, + int retryCount) { LOG.debug("Updating profile {} ", update); try { return endpointService.saveEndpointProfile(update); } catch (KaaOptimisticLockingFailureException ex) { LOG.warn("Failed to update profile {} ", update, ex); if (retryCount > 0) { - EndpointProfileDto stored = endpointService.findEndpointProfileByKeyHash(update.getEndpointKeyHash()); + EndpointProfileDto stored = endpointService.findEndpointProfileByKeyHash( + update.getEndpointKeyHash()); LOG.warn("Going to merge it with stored profile {}", stored); EndpointProfileDto merged = mergeFunction.apply(stored, update); LOG.warn("Merge result: {}", merged); @@ -119,7 +181,8 @@ public EndpointProfileDto registerProfile(RegisterProfileRequest request) { SdkProfileDto sdkProfile = cacheService.getSdkProfileBySdkToken(request.getSdkToken()); LOG.trace("Sdk properties by sdk token: {} found: {}", request.getSdkToken(), sdkProfile); - String profileJson = decodeProfile(request.getProfile(), appSeqNumber.getAppToken(), sdkProfile.getProfileSchemaVersion()); + String profileJson = decodeProfile( + request.getProfile(), appSeqNumber.getAppToken(), sdkProfile.getProfileSchemaVersion()); EndpointObjectHash keyHash = EndpointObjectHash.fromSha1(request.getEndpointKey()); @@ -134,20 +197,24 @@ public EndpointProfileDto registerProfile(RegisterProfileRequest request) { dto.setProfileHash(EndpointObjectHash.fromSha1(request.getProfile()).getData()); try { - Optional endpointRegistrationLookup = endpointRegistrationService.findEndpointRegistrationByEndpointId(endpointId); + Optional endpointRegistrationLookup = + endpointRegistrationService.findEndpointRegistrationByEndpointId(endpointId); if (endpointRegistrationLookup.isPresent()) { - LOG.debug("Endpoint registration information found {}: {}", dto.getEndpointKey(), endpointRegistrationLookup.get()); + LOG.debug("Endpoint registration information found {}: {}", + dto.getEndpointKey(), endpointRegistrationLookup.get()); EndpointRegistrationDto endpointRegistration = endpointRegistrationLookup.get(); - if (endpointRegistration.getServerProfileBody() != null && endpointRegistration.getServerProfileVersion() != null) { + if (endpointRegistration.getServerProfileBody() != null + && endpointRegistration.getServerProfileVersion() != null) { dto.setServerProfileVersion(endpointRegistration.getServerProfileVersion()); dto.setServerProfileBody(endpointRegistration.getServerProfileBody()); } } else { LOG.debug("Endpoint registration information not found {}", dto.getEndpointKey()); } - } catch (EndpointRegistrationServiceException e) { - LOG.error("Failed to lookup registration information for: {}. Reason: {}", dto.getEndpointKey(), e); - throw new RuntimeException(e); + } catch (EndpointRegistrationServiceException ex) { + LOG.error("Failed to lookup registration information for: {}. Reason: {}", + dto.getEndpointKey(), ex); + throw new RuntimeException(ex); } populateVersionStates(appSeqNumber.getTenantId(), dto, sdkProfile); @@ -160,90 +227,43 @@ public EndpointProfileDto registerProfile(RegisterProfileRequest request) { try { cacheService.putEndpointKey(keyHash, KeyUtil.getPublic(dto.getEndpointKey())); - } catch (InvalidKeyException e) { - LOG.error("Can't generate public key for endpoint key: {}. Reason: {}", dto.getEndpointKey(), e); - throw new RuntimeException(e); + } catch (InvalidKeyException ex) { + LOG.error("Can't generate public key for endpoint key: {}. Reason: {}", + dto.getEndpointKey(), ex); + throw new RuntimeException(ex); } return endpointService.saveEndpointProfile(dto); } else { - return updateProfile(new UpdateProfileRequest(request.getAppToken(), keyHash, request.getAccessToken(), request.getProfile(), + return updateProfile(new UpdateProfileRequest( + request.getAppToken(), keyHash, request.getAccessToken(), request.getProfile(), request.getSdkToken())); } } - /* - * (non-Javadoc) - * - * @see org.kaaproject.kaa.server.operations.service.profile.ProfileService# - * updateProfile - * (org.kaaproject.kaa.server.operations.pojo.UpdateProfileRequest) - */ - @Override - public EndpointProfileDto updateProfile(UpdateProfileRequest request) { - LOG.debug("Updating Profile for {}", request.getEndpointKeyHash()); - - EndpointProfileDto dto = endpointService.findEndpointProfileByKeyHash(request.getEndpointKeyHash().getData()); - - AppSeqNumber appSeqNumber = cacheService.getAppSeqNumber(request.getApplicationToken()); - - SdkProfileDto sdkProfile = cacheService.getSdkProfileBySdkToken(request.getSdkToken()); - String profileJson = decodeProfile(request.getProfile(), appSeqNumber.getAppToken(), sdkProfile.getProfileSchemaVersion()); - - Function updateFunction = profile -> { - if (request.getAccessToken() != null) { - profile.setAccessToken(request.getAccessToken()); - } - profile.setClientProfileBody(profileJson); - profile.setProfileHash(EndpointObjectHash.fromSha1(request.getProfile()).getData()); - - populateVersionStates(appSeqNumber.getTenantId(), profile, sdkProfile); - profile.setGroupState(new ArrayList<>()); - profile.setSequenceNumber(0); - return profile; - }; - return updateProfile(updateFunction.apply(dto), (storedProfile, newProfile) -> { - return updateFunction.apply(storedProfile); - }); - } - - @Override - public EndpointProfileDto updateProfile(ClientSyncMetaData metaData, EndpointObjectHash keyHash, boolean useConfigurationRawSchema) { - LOG.debug("Updating Profile for {}", keyHash); - EndpointProfileDto dto = endpointService.findEndpointProfileByKeyHash(keyHash.getData()); - AppSeqNumber appSeqNumber = cacheService.getAppSeqNumber(metaData.getApplicationToken()); - SdkProfileDto sdkProfile = cacheService.getSdkProfileBySdkToken(metaData.getSdkToken()); - - Function updateFunction = profile -> { - populateVersionStates(appSeqNumber.getTenantId(), profile, sdkProfile); - profile.setGroupState(new ArrayList<>()); - profile.setUseConfigurationRawSchema(useConfigurationRawSchema); - profile.setSequenceNumber(0); - return profile; - }; - return updateProfile(updateFunction.apply(dto), (storedProfile, newProfile) -> { - return updateFunction.apply(storedProfile); - }); - } - - protected void populateVersionStates(String tenantId, EndpointProfileDto dto, SdkProfileDto sdkProfile) { + protected void populateVersionStates(String tenantId, + EndpointProfileDto dto, + SdkProfileDto sdkProfile) { dto.setClientProfileVersion(sdkProfile.getProfileSchemaVersion()); dto.setConfigurationVersion(sdkProfile.getConfigurationSchemaVersion()); dto.setUserNfVersion(sdkProfile.getNotificationSchemaVersion()); dto.setLogSchemaVersion(sdkProfile.getLogSchemaVersion()); if (sdkProfile.getAefMapIds() != null) { - List aefMaps = cacheService.getApplicationEventFamilyMapsByIds(sdkProfile.getAefMapIds()); + List aefMaps = cacheService.getApplicationEventFamilyMapsByIds( + sdkProfile.getAefMapIds()); List ecfVersionStates = new ArrayList<>(aefMaps.size()); for (ApplicationEventFamilyMapDto aefMap : aefMaps) { EventClassFamilyVersionStateDto ecfVersionDto = new EventClassFamilyVersionStateDto(); - String ecfId = cacheService.getEventClassFamilyIdByName(new EventClassFamilyIdKey(tenantId, aefMap.getEcfName())); + String ecfId = cacheService.getEventClassFamilyIdByName(new EventClassFamilyIdKey( + tenantId, aefMap.getEcfName())); if (ecfId != null) { ecfVersionDto.setEcfId(ecfId); ecfVersionDto.setVersion(aefMap.getVersion()); ecfVersionStates.add(ecfVersionDto); } else { - LOG.warn("Failed to add ecf version state for ecf name {} and version {}", aefMap.getEcfName(), aefMap.getVersion()); + LOG.warn("Failed to add ecf version state for ecf name {} and version {}", + aefMap.getEcfName(), aefMap.getVersion()); } } dto.setEcfVersionStates(ecfVersionStates); @@ -258,7 +278,8 @@ private String decodeProfile(byte[] profileRaw, String appToken, int schemaVersi .getProfileSchemaByAppAndVersion(new AppVersionKey(appToken, schemaVersion)); String profileSchema = cacheService.getFlatCtlSchemaById(profileSchemaDto.getCtlSchemaId()); - LOG.trace("EndpointProfileSchema by appToken: {} and version: {} found: {}", appToken, schemaVersion, profileSchema); + LOG.trace("EndpointProfileSchema by appToken: {} and version: {} found: {}", + appToken, schemaVersion, profileSchema); String profileJson = GenericAvroConverter.toJson(profileRaw, profileSchema); LOG.trace("Profile json : {} ", profileJson); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/security/OperationsFileKeyStoreService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/security/OperationsFileKeyStoreService.java index e4d09fa222..7fd15c478d 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/security/OperationsFileKeyStoreService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/security/OperationsFileKeyStoreService.java @@ -82,22 +82,22 @@ public void loadKeys() { String publicKeyFullPath = Environment.getServerHomeDir() + "/" + this.publicKeyLocation; LOG.debug("Lookup private key: {}", privateKeyFullPath); LOG.debug("Lookup public key: {}", publicKeyFullPath); - File f = new File(privateKeyFullPath); - if (f.exists()) { + File file = new File(privateKeyFullPath); + if (file.exists()) { try { - privateKey = KeyUtil.getPrivate(f); - } catch (Exception e) { - LOG.debug("Error loading Private Key", e); - throw new RuntimeException(e); //NOSONAR + privateKey = KeyUtil.getPrivate(file); + } catch (Exception ex) { + LOG.debug("Error loading Private Key", ex); + throw new RuntimeException(ex); //NOSONAR } } - f = new File(publicKeyFullPath); - if (f.exists()) { + file = new File(publicKeyFullPath); + if (file.exists()) { try { - publicKey = KeyUtil.getPublic(f); - } catch (Exception e) { - LOG.debug("Error loading Public Key", e); - throw new RuntimeException(e); //NOSONAR + publicKey = KeyUtil.getPublic(file); + } catch (Exception ex) { + LOG.debug("Error loading Public Key", ex); + throw new RuntimeException(ex); //NOSONAR } } if (privateKey == null || publicKey == null) { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/user/DefaultEndpointUserService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/user/DefaultEndpointUserService.java index f54765a678..5213af561d 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/user/DefaultEndpointUserService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/user/DefaultEndpointUserService.java @@ -86,13 +86,16 @@ public List findUserVerifiers(String appId) { } @Override - public EndpointProfileDto attachEndpointToUser(EndpointProfileDto profile, String appToken, String userExternalId) { + public EndpointProfileDto attachEndpointToUser(EndpointProfileDto profile, + String appToken, + String userExternalId) { String tenantId = cacheService.getTenantIdByAppToken(appToken); return endpointService.attachEndpointToUser(userExternalId, tenantId, profile); } @Override - public EndpointAttachResponse attachEndpoint(EndpointProfileDto profile, EndpointAttachRequest endpointAttachRequest) { + public EndpointAttachResponse attachEndpoint(EndpointProfileDto profile, + EndpointAttachRequest endpointAttachRequest) { EndpointAttachResponse response = new EndpointAttachResponse(); response.setRequestId(endpointAttachRequest.getRequestId()); response.setResult(SyncStatus.FAILURE); @@ -100,22 +103,29 @@ public EndpointAttachResponse attachEndpoint(EndpointProfileDto profile, Endpoin String endpointUserId = profile.getEndpointUserId(); if (isNotEmpty(endpointUserId)) { try { - EndpointProfileDto attachedEndpoint = endpointService.attachEndpointToUser(endpointUserId, endpointAttachRequest.getEndpointAccessToken()); + EndpointProfileDto attachedEndpoint = endpointService.attachEndpointToUser( + endpointUserId, endpointAttachRequest.getEndpointAccessToken()); response.setResult(SyncStatus.SUCCESS); response.setEndpointKeyHash(Base64Util.encode(attachedEndpoint.getEndpointKeyHash())); - } catch (DatabaseProcessingException e) { - LOG.warn("[{}] failed to attach endpoint with access token {} and user {}, exception catched: {}", - Base64Util.encode(profile.getEndpointKeyHash()), endpointAttachRequest.getEndpointAccessToken(), profile.getEndpointUserId(), e); + } catch (DatabaseProcessingException ex) { + LOG.warn("[{}] failed to attach endpoint with access token {} and " + + "user {}, exception catched: {}", + Base64Util.encode(profile.getEndpointKeyHash()), + endpointAttachRequest.getEndpointAccessToken(), + profile.getEndpointUserId(), + ex); } } else { - LOG.warn("[{}] received attach endpoint request, but there is no user to attach.", Base64Util.encode(profile.getEndpointKeyHash())); + LOG.warn("[{}] received attach endpoint request, but there is no user to attach.", + Base64Util.encode(profile.getEndpointKeyHash())); } return response; } @Override - public EndpointDetachResponse detachEndpoint(EndpointProfileDto profile, EndpointDetachRequest endpointDetachRequest) { + public EndpointDetachResponse detachEndpoint(EndpointProfileDto profile, + EndpointDetachRequest endpointDetachRequest) { EndpointDetachResponse response = new EndpointDetachResponse(); response.setRequestId(endpointDetachRequest.getRequestId()); response.setResult(SyncStatus.FAILURE); @@ -127,24 +137,31 @@ public EndpointDetachResponse detachEndpoint(EndpointProfileDto profile, Endpoin endpointService.detachEndpointFromUser(profile); response.setResult(SyncStatus.SUCCESS); } else { - EndpointProfileDto detachEndpoint = endpointService.findEndpointProfileByKeyHash(endpointKeyHash); + EndpointProfileDto detachEndpoint = endpointService.findEndpointProfileByKeyHash( + endpointKeyHash); if (detachEndpoint != null) { - if (detachEndpoint.getEndpointUserId() != null && detachEndpoint.getEndpointUserId().equals(profile.getEndpointUserId())) { + if (detachEndpoint.getEndpointUserId() != null + && detachEndpoint.getEndpointUserId().equals(profile.getEndpointUserId())) { endpointService.detachEndpointFromUser(detachEndpoint); response.setResult(SyncStatus.SUCCESS); } else { - LOG.warn("[{}] received detach endpoint request, but requested {} and current {} user mismatch.", - Base64Util.encode(profile.getEndpointKeyHash()), profile.getEndpointUserId(), detachEndpoint.getEndpointUserId()); + LOG.warn("[{}] received detach endpoint request, " + + "but requested {} and current {} user mismatch.", + Base64Util.encode(profile.getEndpointKeyHash()), + profile.getEndpointUserId(), + detachEndpoint.getEndpointUserId()); } } else { - LOG.warn("[{}] received detach endpoint request, for not existing endpoint.", Base64Util.encode(profile.getEndpointKeyHash())); + LOG.warn("[{}] received detach endpoint request, for not existing endpoint.", + Base64Util.encode(profile.getEndpointKeyHash())); } } - } catch (DatabaseProcessingException e) { - LOG.warn("[{}] failed to detach endpoint {}, exception catched: ", profile, e); + } catch (DatabaseProcessingException ex) { + LOG.warn("[{}] failed to detach endpoint {}, exception catched: ", profile, ex); } } else { - LOG.warn("[{}] detach endpoint request {} or profile {} is not valid", Base64Util.encode(profile.getEndpointKeyHash()), endpointDetachRequest, + LOG.warn("[{}] detach endpoint request {} or profile {} is not valid", + Base64Util.encode(profile.getEndpointKeyHash()), endpointDetachRequest, profile); } @@ -152,7 +169,8 @@ public EndpointDetachResponse detachEndpoint(EndpointProfileDto profile, Endpoin } protected boolean isValid(EndpointDetachRequest endpointDetachRequest) { - return endpointDetachRequest.getEndpointKeyHash() != null && !endpointDetachRequest.getEndpointKeyHash().isEmpty(); + return endpointDetachRequest.getEndpointKeyHash() != null + && !endpointDetachRequest.getEndpointKeyHash().isEmpty(); } protected boolean isNotEmpty(String userId) { @@ -160,13 +178,16 @@ protected boolean isNotEmpty(String userId) { } @Override - public EventListenersResponse findListeners(EndpointProfileDto profile, String appToken, EventListenersRequest request) { + public EventListenersResponse findListeners(EndpointProfileDto profile, + String appToken, + EventListenersRequest request) { if (profile.getEndpointUserId() == null || profile.getEndpointUserId().isEmpty()) { LOG.info("Can't find listeners for unassigned endpoint!"); return new EventListenersResponse(request.getRequestId(), null, SyncStatus.FAILURE); } - List endpointProfiles = endpointService.findEndpointProfilesByUserId(profile.getEndpointUserId()); + List endpointProfiles = endpointService.findEndpointProfilesByUserId( + profile.getEndpointUserId()); if (endpointProfiles.size() <= 1) { LOG.info("There is only one endpoint(current) assigned to this user!"); List emptyList = Collections.emptyList(); @@ -177,8 +198,10 @@ public EventListenersResponse findListeners(EndpointProfileDto profile, String a Set eventClassIntersectionSet = null; for (String eventClassFqn : request.getEventClassFqns()) { Set eventClassSet = new HashSet<>(); - LOG.debug("Lookup event class family id using tenant [{}] and event class fqn {}", tenantId, eventClassFqn); - String ecfId = cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(tenantId, eventClassFqn)); + LOG.debug("Lookup event class family id using tenant [{}] and event class fqn {}", + tenantId, eventClassFqn); + String ecfId = cacheService.getEventClassFamilyIdByEventClassFqn( + new EventClassFqnKey(tenantId, eventClassFqn)); int version = 0; for (EventClassFamilyVersionStateDto ecfVersionDto : profile.getEcfVersionStates()) { if (ecfVersionDto.getEcfId().equals(ecfId)) { @@ -187,8 +210,10 @@ public EventListenersResponse findListeners(EndpointProfileDto profile, String a } } if (version > 0) { - LOG.debug("Load recepient keys using tenant [{}] event class {} and version {}", tenantId, eventClassFqn, version); - Set recipientKeys = cacheService.getRouteKeys(new EventClassFqnVersion(tenantId, eventClassFqn, version)); + LOG.debug("Load recepient keys using tenant [{}] event class {} and version {}", + tenantId, eventClassFqn, version); + Set recipientKeys = cacheService.getRouteKeys( + new EventClassFqnVersion(tenantId, eventClassFqn, version)); for (EndpointProfileDto endpointProfile : endpointProfiles) { if (endpointProfile.getId().equals(profile.getId())) { @@ -196,20 +221,24 @@ public EventListenersResponse findListeners(EndpointProfileDto profile, String a } for (RouteTableKey routeTableKey : recipientKeys) { - AppSeqNumber endpointProfileSeqNumber = cacheService.getAppSeqNumber(routeTableKey.getAppToken()); + AppSeqNumber endpointProfileSeqNumber = cacheService.getAppSeqNumber( + routeTableKey.getAppToken()); if (!endpointProfile.getApplicationId().equals(endpointProfileSeqNumber.getAppId())) { continue; } for (EventClassFamilyVersionStateDto ecfVersionDto : profile.getEcfVersionStates()) { if (ecfVersionDto.getEcfId().equals(routeTableKey.getEcfVersion().getEcfId()) && ecfVersionDto.getVersion() == routeTableKey.getEcfVersion().getVersion()) { - eventClassSet.add(EndpointObjectHash.fromBytes(endpointProfile.getEndpointKeyHash())); + eventClassSet.add( + EndpointObjectHash.fromBytes(endpointProfile.getEndpointKeyHash())); } } } } } else { - LOG.warn("Lookup event class family version using tenant [{}] and event class fqn {} FAILED!", tenantId, eventClassFqn); + LOG.warn("Lookup event class family version using tenant [{}] and event class fqn {} " + + "FAILED!", + tenantId, eventClassFqn); } if (eventClassIntersectionSet == null) { eventClassIntersectionSet = eventClassSet; diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/user/EndpointUserService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/user/EndpointUserService.java index 0b13f38aaf..46a1a1eb62 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/user/EndpointUserService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/user/EndpointUserService.java @@ -33,12 +33,18 @@ public interface EndpointUserService { List findUserVerifiers(String appId); - EndpointProfileDto attachEndpointToUser(EndpointProfileDto profile, String appToken, String userExternalId); + EndpointProfileDto attachEndpointToUser(EndpointProfileDto profile, + String appToken, + String userExternalId); - EndpointAttachResponse attachEndpoint(EndpointProfileDto profile, EndpointAttachRequest endpointAttachRequest); + EndpointAttachResponse attachEndpoint(EndpointProfileDto profile, + EndpointAttachRequest endpointAttachRequest); - EndpointDetachResponse detachEndpoint(EndpointProfileDto profile, EndpointDetachRequest endpointDetachRequest); + EndpointDetachResponse detachEndpoint(EndpointProfileDto profile, + EndpointDetachRequest endpointDetachRequest); - EventListenersResponse findListeners(EndpointProfileDto profile, String appToken, EventListenersRequest request); + EventListenersResponse findListeners(EndpointProfileDto profile, + String appToken, + EventListenersRequest request); } diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/AbstractCTLMigration.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/AbstractCtlMigration.java similarity index 79% rename from server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/AbstractCTLMigration.java rename to server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/AbstractCtlMigration.java index 026d77b330..877ea38f31 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/AbstractCTLMigration.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/AbstractCtlMigration.java @@ -30,13 +30,13 @@ import java.sql.SQLException; import java.util.List; -public abstract class AbstractCTLMigration { +public abstract class AbstractCtlMigration { protected Connection connection; protected QueryRunner runner; protected DataDefinition dd; protected Long idShift; - public AbstractCTLMigration(Connection connection) { + public AbstractCtlMigration(Connection connection) { this.connection = connection; runner = new QueryRunner(); dd = new DataDefinition(connection); @@ -50,22 +50,26 @@ public void beforeTransform() throws SQLException { protected List transform() throws SQLException { // fetch schemas of appropriate feature like configuration - List schemas = runner.query(connection, "select " + - "f.id as id, created_time as createdTime, created_username as createdUsername, " + - "description, name, schems, version, application_id as appId " + - "from " + getPrefixTableName() + "_schems f join schems s on f.id = s.id", new BeanListHandler<>(Schema.class)); + List schemas = runner.query(connection, "select " + + "f.id as id, created_time as createdTime, created_username as createdUsername, " + + "description, name, schems, version, application_id as appId " + + "from " + getPrefixTableName() + "_schems f join schems s on f.id = s.id", + new BeanListHandler<>(Schema.class)); // delete the fetched ids from schema table String toDelete = schemas.stream().map(s -> s.getId().toString()).collect(joining(", ")); - String NOT_EMPTY_ID_SET = "^[\\s]*([0-9]+(\\,\\s)?)+"; - if (toDelete.matches(NOT_EMPTY_ID_SET)) { + String notEmptyIdSet = "^[\\s]*([0-9]+(\\,\\s)?)+"; + if (toDelete.matches(notEmptyIdSet)) { runner.update(connection, "delete from schems where id in (" + toDelete + ")"); } // shift ids in order to avoid PK constraint violation during adding record to base_schema - Long shift = runner.query(connection, "select max(id) as max_id from " + getPrefixTableName() + "_schems", rs -> rs.next() ? rs.getLong("max_id") : null); + Long shift = runner.query(connection, "select max(id) as max_id from " + getPrefixTableName() + + "_schems", + rs -> rs.next() ? rs.getLong("max_id") : null); idShift = BaseSchemaIdCounter.getInstance().getAndShift(shift); - runner.update(connection, "update " + getPrefixTableName() + "_schems set id = id + " + idShift + " order by id desc"); + runner.update(connection, "update " + getPrefixTableName() + "_schems set id = id + " + + idShift + " order by id desc"); schemas.forEach(s -> s.setId(s.getId() + idShift)); return schemas; diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlConfigurationMigration.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlConfigurationMigration.java index cf4b027357..0b37490bd3 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlConfigurationMigration.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlConfigurationMigration.java @@ -22,7 +22,7 @@ import java.sql.Connection; import java.sql.SQLException; -public class CtlConfigurationMigration extends AbstractCTLMigration { +public class CtlConfigurationMigration extends AbstractCtlMigration { public CtlConfigurationMigration(Connection connection) { diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlEventsMigration.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlEventsMigration.java index aef419ce36..ecd86f3e7e 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlEventsMigration.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlEventsMigration.java @@ -34,7 +34,7 @@ import java.util.ArrayList; import java.util.List; -public class CtlEventsMigration extends AbstractCTLMigration { +public class CtlEventsMigration extends AbstractCtlMigration { private static final String EVENT_SCHEMA_VERSION_TABLE_NAME = "event_schems_versions"; private static final String EVENT_CLASS_FAMILY_TABLE_NAME = "events_class_family"; private static final String EVENT_CLASS_FAMILY_VERSION_TABLE_NAME = @@ -185,7 +185,7 @@ private boolean ecBelongToThisFamilyVersion(EventClass ec, EventSchemaVersion es String namespace = jsonNode.get("namespace").asText(); String name = jsonNode.get("name").asText(); - return esv.getSchems().contains(name) && esv.getSchems().contains(namespace); + return esv.getSchemas().contains(name) && esv.getSchemas().contains(namespace); } catch (IOException ex) { System.err.println("Failed to read EventClass schema: " + ec); } diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlLogMigration.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlLogMigration.java index 6e1f8fe16f..878f5e865d 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlLogMigration.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlLogMigration.java @@ -18,7 +18,7 @@ import java.sql.Connection; -public class CtlLogMigration extends AbstractCTLMigration { +public class CtlLogMigration extends AbstractCtlMigration { public static final String LOG_SCHEMA_PREFIX_TABLE_NAME = "log"; diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlNotificationMigration.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlNotificationMigration.java index 32d83c8796..a15be9d0dd 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlNotificationMigration.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlNotificationMigration.java @@ -44,7 +44,7 @@ import java.util.List; -public class CtlNotificationMigration extends AbstractCTLMigration { +public class CtlNotificationMigration extends AbstractCtlMigration { private MongoClient client; private Cluster cluster; private String dbName; diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/MigrateData.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/MigrateData.java index 3722312c54..cdf8501608 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/MigrateData.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/MigrateData.java @@ -87,7 +87,7 @@ public static void main(String[] args) { BaseSchemaIdCounter.setInitValue(maxId); UpdateUuidsMigration updateUuidsMigration = new UpdateUuidsMigration(conn, options.getHost(), options.getDbName(), options.getNoSql()); EndpointProfileMigration endpointProfileMigration = new EndpointProfileMigration(options.getHost(), options.getDbName(), options.getNoSql()); - List migrationList = new ArrayList<>(); + List migrationList = new ArrayList<>(); migrationList.add(new CtlConfigurationMigration(conn)); migrationList.add(new CtlEventsMigration(conn)); migrationList.add(new CtlNotificationMigration(conn, options.getHost(), options.getDbName(), options.getNoSql())); @@ -101,12 +101,12 @@ public static void main(String[] args) { endpointProfileMigration.transform(); //before phase - for (AbstractCTLMigration m : migrationList) { + for (AbstractCtlMigration m : migrationList) { m.beforeTransform(); } // transform phase - for (AbstractCTLMigration m : migrationList) { + for (AbstractCtlMigration m : migrationList) { schemas.addAll(m.transform()); } @@ -117,7 +117,7 @@ public static void main(String[] args) { recordsCreation.create(ctlToSchemas); //after phase - for (AbstractCTLMigration m : migrationList) { + for (AbstractCtlMigration m : migrationList) { m.afterTransform(); } diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/UpdateUuidsMigration.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/UpdateUuidsMigration.java index 01dcafc739..e016790b3d 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/UpdateUuidsMigration.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/UpdateUuidsMigration.java @@ -69,7 +69,7 @@ public void transform() throws IOException, SQLException { ResultSetHandler> rsHandler = new BeanListHandler(Configuration.class); List configs = run.query(connection, "SELECT * FROM configuration", rsHandler); for (Configuration config : configs) { - JsonNode json = new ObjectMapper().readTree(config.getConfiguration_body()); + JsonNode json = new ObjectMapper().readTree(config.getConfigurationBody()); JsonNode jsonEncoded = encodeUuids(json); byte[] encodedConfigurationBody = jsonEncoded.toString().getBytes(); diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/Configuration.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/Configuration.java index a9bb39ecc0..06a5ea70bf 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/Configuration.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/Configuration.java @@ -22,19 +22,19 @@ public class Configuration implements Serializable { private static final long serialVersionUID = -1176562073; - private byte[] configuration_body; - private Integer configuration_schems_version; + private byte[] configurationBody; + private Integer configurationSchemasVersion; private Long id; - private Long configuration_schems_id; + private Long configurationSchemasId; public Configuration() { } public Configuration(Configuration value) { - this.configuration_body = value.configuration_body; - this.configuration_schems_version = value.configuration_schems_version; + this.configurationBody = value.configurationBody; + this.configurationSchemasVersion = value.configurationSchemasVersion; this.id = value.id; - this.configuration_schems_id = value.configuration_schems_id; + this.configurationSchemasId = value.configurationSchemasId; } public Configuration( @@ -43,26 +43,26 @@ public Configuration( Long id, Long configurationSchemsId ) { - this.configuration_body = configurationBody; - this.configuration_schems_version = configurationSchemsVersion; + this.configurationBody = configurationBody; + this.configurationSchemasVersion = configurationSchemsVersion; this.id = id; - this.configuration_schems_id = configurationSchemsId; + this.configurationSchemasId = configurationSchemsId; } - public byte[] getConfiguration_body() { - return this.configuration_body; + public byte[] getConfigurationBody() { + return this.configurationBody; } - public void setConfiguration_body(byte[] configuration_body) { - this.configuration_body = configuration_body; + public void setConfigurationBody(byte[] configurationBody) { + this.configurationBody = configurationBody; } - public Integer getConfiguration_schems_version() { - return this.configuration_schems_version; + public Integer getConfigurationSchemasVersion() { + return this.configurationSchemasVersion; } - public void setConfiguration_schems_version(Integer configuration_schems_version) { - this.configuration_schems_version = configuration_schems_version; + public void setConfigurationSchemasVersion(Integer configurationSchemasVersion) { + this.configurationSchemasVersion = configurationSchemasVersion; } public Long getId() { @@ -73,22 +73,22 @@ public void setId(Long id) { this.id = id; } - public Long getConfiguration_schems_id() { - return this.configuration_schems_id; + public Long getConfigurationSchemasId() { + return this.configurationSchemasId; } - public void setConfiguration_schems_id(Long configuration_schems_id) { - this.configuration_schems_id = configuration_schems_id; + public void setConfigurationSchemasId(Long configurationSchemasId) { + this.configurationSchemasId = configurationSchemasId; } @Override public String toString() { StringBuilder sb = new StringBuilder("configuration.Configuration["); - sb.append("configuration_body=").append(new String(configuration_body)); - sb.append(", configuration_schems_version=").append(configuration_schems_version); + sb.append("configurationBody=").append(new String(configurationBody)); + sb.append(", configurationSchemasVersion=").append(configurationSchemasVersion); sb.append(", id=").append(id); - sb.append(", configuration_schems_id=").append(configuration_schems_id); + sb.append(", configurationSchemasId=").append(configurationSchemasId); sb.append("]"); return sb.toString(); diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/Ctl.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/Ctl.java index 259699e389..529ec345d8 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/Ctl.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/Ctl.java @@ -29,15 +29,21 @@ public Ctl(Long id, CtlMetaInfo metaInfo, String defaultRecord) { } @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + public boolean equals(Object obj) { + if (this == obj) { + return true; + } - Ctl ctl = (Ctl) o; + if (obj == null || getClass() != obj.getClass()) { + return false; + } - if (!metaInfo.equals(ctl.metaInfo)) return false; - return defaultRecord.equals(ctl.defaultRecord); + Ctl ctl = (Ctl) obj; + if (!metaInfo.equals(ctl.metaInfo)) { + return false; + } + return defaultRecord.equals(ctl.defaultRecord); } @Override diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/EventSchemaVersion.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/EventSchemaVersion.java index cde9fe403a..231ff34ba1 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/EventSchemaVersion.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/EventSchemaVersion.java @@ -18,9 +18,9 @@ public class EventSchemaVersion { private Long id; - private String schems; - private Long created_time; - private String created_username; + private String schemas; + private Long createdTime; + private String createdUsername; public Long getId() { return id; @@ -30,43 +30,36 @@ public void setId(Long id) { this.id = id; } - public String getSchems() { - return schems; + public String getSchemas() { + return schemas; } - public void setSchems(String schems) { - this.schems = schems; + public void setSchemas(String schemas) { + this.schemas = schemas; } @Override public String toString() { - return "EventSchemaVersion{" + - "id=" + id + - ", schems=" + schems + - '}'; + return "EventSchemaVersion{" + + "id=" + id + + ", schemas=" + schemas + + '}'; } - public Long getCreatedTime() { - return created_time; - } - public Long getCreated_time() { - return created_time; + public Long getCreatedTime() { + return createdTime; } - public void setCreated_time(Long created_time) { - this.created_time = created_time; + public void setCreatedTime(Long createdTime) { + this.createdTime = createdTime; } public String getCreatedUsername() { - return created_username; - } - - public String getCreated_username() { - return created_username; + return createdUsername; } - public void setCreated_username(String created_username) { - this.created_username = created_username; + public void setCreatedUsername(String createdUsername) { + this.createdUsername = createdUsername; } } diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/FlatCtl.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/FlatCtl.java index 7243d90a2d..c3bb1606fb 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/FlatCtl.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/FlatCtl.java @@ -79,7 +79,8 @@ public void setTenantId(Long tenantId) { } public Ctl toCtl() throws IOException, ConfigurationGenerationException { - return new Ctl(ctlId, new CtlMetaInfo(metaInfoId, fqn, appId, tenantId), generateDefaultRecord()); + return new Ctl(ctlId, new CtlMetaInfo( + metaInfoId, fqn, appId, tenantId), generateDefaultRecord()); } @@ -87,7 +88,8 @@ private String generateDefaultRecord() throws ConfigurationGenerationException, org.apache.avro.Schema schemaBody = new org.apache.avro.Schema.Parser().parse(body); String fqn = schemaBody.getFullName(); RawSchema rawSchema = new RawSchema(schemaBody.toString()); - DefaultRecordGenerationAlgorithm algotithm = new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory()); - return algotithm.getRootData().getRawData(); + DefaultRecordGenerationAlgorithm algorithm = + new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory()); + return algorithm.getRootData().getRawData(); } } diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/datadefinition/DataDefinition.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/datadefinition/DataDefinition.java index bbd804c8ce..6d28452a93 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/datadefinition/DataDefinition.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/datadefinition/DataDefinition.java @@ -26,7 +26,10 @@ import java.util.List; public class DataDefinition { - private static final String QUERY_FIND_FK_NAME = "SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'kaa' AND TABLE_NAME = '%s' and referenced_table_name='%s'"; + private static final String QUERY_FIND_FK_NAME = "SELECT CONSTRAINT_NAME FROM " + + "INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE REFERENCED_TABLE_SCHEMA = 'kaa'" + + " AND TABLE_NAME = '%s' and referenced_table_name='%s'"; + private Connection connection; public DataDefinition(Connection connection) { @@ -39,7 +42,7 @@ public AlterBuilder alterTable(String tableName) { /** * Drop foreign key with autogenerated name based on the table where constrain declared and - * referenced table name + * referenced table name. */ public void dropUnnamedFk(String tableName, String referencedTableName) throws SQLException { QueryRunner runner = new QueryRunner(); @@ -68,29 +71,31 @@ public AlterBuilder add(Constraint constraint) { public void execute() throws SQLException { StringBuilder sql = new StringBuilder("ALTER TABLE " + tableName + "\n"); for (int i = 0; i < addConstrains.size(); i++) { - Constraint c = addConstrains.get(i); - switch (c.getType()) { + Constraint constraint = addConstrains.get(i); + switch (constraint.getType()) { case FK: sql.append(format("ADD CONSTRAINT %s FOREIGN KEY (%s) REFERENCES %s(%s) \n", - c.getConstraintName(), - c.getField(), - c.getReferencedTable(), - c.getReferencedField()) + constraint.getConstraintName(), + constraint.getField(), + constraint.getReferencedTable(), + constraint.getReferencedField()) ); - if (c.getOnDeleteOpt() != null) { - sql.append("ON DELETE " + c.getOnDeleteOpt() + "\n"); + if (constraint.getOnDeleteOpt() != null) { + sql.append("ON DELETE " + constraint.getOnDeleteOpt() + "\n"); } - if (c.getOnUpdateOpt() != null) { - sql.append("ON UPDATE " + c.getOnUpdateOpt() + "\n"); + if (constraint.getOnUpdateOpt() != null) { + sql.append("ON UPDATE " + constraint.getOnUpdateOpt() + "\n"); } break; case PK: - sql.append(format("ADD CONSTRAINT %s PRIMARY KEY (%s)\n", c.getConstraintName(), c.getField())); + sql.append(format("ADD CONSTRAINT %s PRIMARY KEY (%s)\n", + constraint.getConstraintName(), constraint.getField())); break; case UNIQUE: - sql.append(format("ADD CONSTRAINT %s UNIQUE (%s)\n", c.getConstraintName(), c.getField())); + sql.append(format("ADD CONSTRAINT %s UNIQUE (%s)\n", + constraint.getConstraintName(), constraint.getField())); break; default: break;