diff --git a/server/flume/src/main/java/org/kaaproject/kaa/server/flume/sink/hdfs/KaaEventFactory.java b/server/flume/src/main/java/org/kaaproject/kaa/server/flume/sink/hdfs/KaaEventFactory.java index 49d0745fe5..bebaaf696d 100644 --- a/server/flume/src/main/java/org/kaaproject/kaa/server/flume/sink/hdfs/KaaEventFactory.java +++ b/server/flume/src/main/java/org/kaaproject/kaa/server/flume/sink/hdfs/KaaEventFactory.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.kaaproject.kaa.server.flume.sink.hdfs; import com.google.common.collect.Lists; diff --git a/server/flume/src/main/java/org/kaaproject/kaa/server/flume/sink/hdfs/KaaHdfsSink.java b/server/flume/src/main/java/org/kaaproject/kaa/server/flume/sink/hdfs/KaaHdfsSink.java index 99fe408048..7a997c1f4e 100644 --- a/server/flume/src/main/java/org/kaaproject/kaa/server/flume/sink/hdfs/KaaHdfsSink.java +++ b/server/flume/src/main/java/org/kaaproject/kaa/server/flume/sink/hdfs/KaaHdfsSink.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package org.kaaproject.kaa.server.flume.sink.hdfs; import com.google.common.base.Preconditions; @@ -68,9 +69,11 @@ public class KaaHdfsSink extends AbstractSink implements Configurable, Configura private static final Logger LOG = LoggerFactory.getLogger(KaaHdfsSink.class); /** * Singleton credential manager that manages static credentials for the - * entire JVM + * entire JVM. */ - private static final AtomicReference staticLogin = new AtomicReference<>(); //NOSONAR + private static final AtomicReference staticLogin = + new AtomicReference<>(); //NOSONAR + private boolean started = false; private KaaEventFactory eventFactory; private Context context; @@ -136,10 +139,10 @@ private static synchronized UserGroupInformation kerberosLogin( UserGroupInformation curUser = null; try { curUser = UserGroupInformation.getLoginUser(); - } catch (IOException e) { + } catch (IOException ex) { // not a big deal but this shouldn't typically happen because it will // generally fall back to the UNIX user - LOG.debug("Unable to get login user before Kerberos auth attempt.", e); + LOG.debug("Unable to get login user before Kerberos auth attempt.", ex); } // we already have logged in successfully @@ -150,8 +153,8 @@ private static synchronized UserGroupInformation kerberosLogin( // no principal found } else { - LOG.info("{}: Attempting kerberos login as principal ({}) from keytab " + - "file ({})", new Object[]{sink, principal, keytab}); + LOG.info("{}: Attempting kerberos login as principal ({}) from keytab file ({})", + new Object[]{sink, principal, keytab}); // attempt static kerberos login UserGroupInformation.loginUserFromKeytab(principal, keytab); @@ -170,18 +173,24 @@ public void configure(Context context) { statisticsInterval = context.getLong(CONFIG_STATISTICS_INTERVAL, DEFAULT_STATISTICS_INTERVAL); // writers - threadsPoolSize = context.getInteger(CONFIG_HDFS_THREAD_POOL_SIZE, DEFAULT_HDFS_THREAD_POOL_SIZE); - rollTimerPoolSize = context.getInteger(CONFIG_HDFS_ROLL_TIMER_POOL_SIZE, DEFAULT_HDFS_ROLL_TIMER_POOL_SIZE); + threadsPoolSize = context.getInteger( + CONFIG_HDFS_THREAD_POOL_SIZE, DEFAULT_HDFS_THREAD_POOL_SIZE); + + rollTimerPoolSize = context.getInteger( + CONFIG_HDFS_ROLL_TIMER_POOL_SIZE, DEFAULT_HDFS_ROLL_TIMER_POOL_SIZE); maxOpenFiles = context.getInteger(CONFIG_HDFS_MAX_OPEN_FILES, DEFAULT_HDFS_MAX_OPEN_FILES); - cacheCleanupInterval = context.getInteger(CONFIG_HDFS_CACHE_CLEANUP_INTERVAL, DEFAULT_HDFS_CACHE_CLEANUP_INTERVAL) * 1000; - writerExpirationInterval = context.getInteger(CONFIG_HDFS_WRITER_EXPIRATION_INTERVAL, DEFAULT_HDFS_WRITER_EXPIRATION_INTERVAL); + cacheCleanupInterval = context.getInteger( + CONFIG_HDFS_CACHE_CLEANUP_INTERVAL, DEFAULT_HDFS_CACHE_CLEANUP_INTERVAL) * 1000; + writerExpirationInterval = context.getInteger( + CONFIG_HDFS_WRITER_EXPIRATION_INTERVAL, DEFAULT_HDFS_WRITER_EXPIRATION_INTERVAL); callTimeout = context.getLong(CONFIG_HDFS_CALL_TIMEOUT, DEFAULT_HDFS_CALL_TIMEOUT); rollInterval = context.getLong(CONFIG_HDFS_ROLL_INTERVAL, DEFAULT_HDFS_ROLL_INTERVAL); rollSize = context.getLong(CONFIG_HDFS_ROLL_SIZE, DEFAULT_HDFS_ROLL_SIZE); rollCount = context.getLong(CONFIG_HDFS_ROLL_COUNT, DEFAULT_HDFS_ROLL_COUNT); batchSize = context.getLong(CONFIG_HDFS_BATCH_SIZE, DEFAULT_HDFS_BATCH_SIZE); - defaultBlockSize = context.getLong(CONFIG_HDFS_DEFAULT_BLOCK_SIZE, DEFAULT_HDFS_DEFAULT_BLOCK_SIZE); + defaultBlockSize = context.getLong( + CONFIG_HDFS_DEFAULT_BLOCK_SIZE, DEFAULT_HDFS_DEFAULT_BLOCK_SIZE); filePrefix = context.getString(CONFIG_HDFS_FILE_PREFIX, DEFAULT_HDFS_FILE_PREFIX); @@ -217,11 +226,11 @@ private T callWithTimeout(Callable callable) } else { return future.get(); } - } catch (TimeoutException eT) { + } catch (TimeoutException ex) { future.cancel(true); sinkCounter.incrementConnectionFailedCount(); throw new IOException("Callable timed out after " + callTimeout + " ms", - eT); + ex); } catch (ExecutionException e1) { sinkCounter.incrementConnectionFailedCount(); Throwable cause = e1.getCause(); @@ -270,7 +279,8 @@ public Status process() throws EventDeliveryException { // cacheCleanupStartInterval = System.currentTimeMillis(); //} - Map> incomingEventsMap = eventFactory.processIncomingFlumeEvent(event); + Map> incomingEventsMap = + eventFactory.processIncomingFlumeEvent(event); if (incomingEventsMap == null || incomingEventsMap.isEmpty()) { if (LOG.isWarnEnabled()) { LOG.warn("Unable to parse incoming event: " + event); @@ -315,9 +325,9 @@ public Status process() throws EventDeliveryException { return Status.BACKOFF; } return Status.READY; - } catch (IOException eIO) { + } catch (IOException eIo) { transaction.rollback(); - LOG.warn("HDFS IO error", eIO); + LOG.warn("HDFS IO error", eIo); return Status.BACKOFF; } catch (Throwable th) { //NOSONAR transaction.rollback(); @@ -343,8 +353,8 @@ public void start() { new ThreadFactoryBuilder().setNameFormat(timeoutName).build()); String rollerName = "hdfs-" + getName() + "-roll-timer-%d"; - timedRollerPool = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(rollTimerPoolSize, - new ThreadFactoryBuilder().setNameFormat(rollerName).build()); + timedRollerPool = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool( + rollTimerPoolSize, new ThreadFactoryBuilder().setNameFormat(rollerName).build()); if (statisticsInterval > 0) { String statisticsName = "hdfs-" + getName() + "-statistics-%d"; @@ -354,11 +364,12 @@ public void start() { Runnable action = new Runnable() { @Override public void run() { - LOG.info("Statistics: Drain attempt events: " + sinkCounter.getEventDrainAttemptCount() + "; " + - "Drain success events: " + sinkCounter.getEventDrainSuccessCount()); + LOG.info("Statistics: Drain attempt events: " + sinkCounter.getEventDrainAttemptCount() + + "; " + "Drain success events: " + sinkCounter.getEventDrainSuccessCount()); } }; - statisticsFuture = statisticsPool.scheduleWithFixedDelay(action, 0, statisticsInterval, TimeUnit.SECONDS); + statisticsFuture = statisticsPool.scheduleWithFixedDelay( + action, 0, statisticsInterval, TimeUnit.SECONDS); } cacheCleanupStartInterval = System.currentTimeMillis(); @@ -374,11 +385,11 @@ public void run() { proxyTicket, sinkCounter); - writerCache = CacheBuilder.newBuilder(). - maximumSize(maxOpenFiles). - expireAfterWrite(writerExpirationInterval, TimeUnit.SECONDS). - removalListener(this). - build(bucketWriterLoader); + writerCache = CacheBuilder.newBuilder() + .maximumSize(maxOpenFiles) + .expireAfterWrite(writerExpirationInterval, TimeUnit.SECONDS) + .removalListener(this) + .build(bucketWriterLoader); writerFlushMap = new HashMap(); @@ -401,8 +412,8 @@ public void stop() { try { close(entry.getValue()); } catch (Exception ex) { - LOG.warn("Exception while closing " + entry.getKey() + ". " + - "Exception follows.", ex); + LOG.warn("Exception while closing " + entry.getKey() + ". " + + "Exception follows.", ex); if (ex instanceof InterruptedException) { Thread.currentThread().interrupt(); } @@ -420,7 +431,9 @@ public void stop() { try { while (execService.isTerminated() == false) { execService.awaitTermination( - Math.max(ConfigurationConstants.DEFAULT_HDFS_CALL_TIMEOUT, callTimeout), TimeUnit.MILLISECONDS); + Math.max( + ConfigurationConstants.DEFAULT_HDFS_CALL_TIMEOUT, callTimeout), + TimeUnit.MILLISECONDS); } } catch (InterruptedException ex) { LOG.warn("shutdown interrupted on " + execService, ex); @@ -440,8 +453,8 @@ public void stop() { @Override public String toString() { - return "{ Sink type:" + getClass().getSimpleName() + ", name:" + getName() + - " }"; + return "{ Sink type:" + getClass().getSimpleName() + ", name:" + getName() + + " }"; } public long getEventDrainSuccessCount() { @@ -459,10 +472,10 @@ public void onRemoval( try { writerFlushMap.remove(key); writer.close(); - } catch (IOException e) { - LOG.warn(entry.getKey().toString(), e); - } catch (InterruptedException e) { - LOG.warn(entry.getKey().toString(), e); + } catch (IOException ex) { + LOG.warn(entry.getKey().toString(), ex); + } catch (InterruptedException ex) { + LOG.warn(entry.getKey().toString(), ex); Thread.currentThread().interrupt(); } } @@ -503,9 +516,9 @@ private boolean authenticate() { // resolves _HOST pattern using standard Hadoop search/replace // via DNS lookup when 2nd argument is empty principal = SecurityUtil.getServerPrincipal(kerbConfPrincipal, ""); - } catch (IOException e) { + } catch (IOException ex) { LOG.error("Host lookup error resolving kerberos principal (" - + kerbConfPrincipal + "). Exception follows.", e); + + kerbConfPrincipal + "). Exception follows.", ex); return false; } @@ -520,9 +533,9 @@ private boolean authenticate() { // since we don't have to be unnecessarily protective if they switch all // HDFS sinks to use a different principal all at once. Preconditions.checkState(prevUser == null || prevUser.equals(newUser), - "Cannot use multiple kerberos principals in the same agent. " + - " Must restart agent to use new principal or keytab. " + - "Previous = %s, New = %s", prevUser, newUser); + "Cannot use multiple kerberos principals in the same agent. " + + " Must restart agent to use new principal or keytab. " + + "Previous = %s, New = %s", prevUser, newUser); // attempt to use cached credential if the user is the same // this is polite and should avoid flooding the KDC with auth requests @@ -530,9 +543,9 @@ private boolean authenticate() { if (prevUser != null && prevUser.equals(newUser)) { try { curUser = UserGroupInformation.getLoginUser(); - } catch (IOException e) { - LOG.warn("User unexpectedly had no active login. Continuing with " + - "authentication", e); + } catch (IOException ex) { + LOG.warn("User unexpectedly had no active login. Continuing with " + + "authentication", ex); } } @@ -540,10 +553,10 @@ private boolean authenticate() { try { // static login kerberosLogin(this, principal, kerbKeytab); - } catch (IOException e) { + } catch (IOException ex) { LOG.error("Authentication or file read error while attempting to " + "login as kerberos principal (" + principal + ") using " - + "keytab (" + kerbKeytab + "). Exception follows.", e); + + "keytab (" + kerbKeytab + "). Exception follows.", ex); return false; } } else { @@ -560,8 +573,8 @@ private boolean authenticate() { try { proxyTicket = UserGroupInformation.createProxyUser( proxyUserName, UserGroupInformation.getLoginUser()); - } catch (IOException e) { - LOG.error("Unable to login as proxy user. Exception follows.", e); + } catch (IOException ex) { + LOG.error("Unable to login as proxy user. Exception follows.", ex); return false; } } @@ -572,9 +585,9 @@ private boolean authenticate() { } else if (useSecurity) { try { ugi = UserGroupInformation.getLoginUser(); - } catch (IOException e) { - LOG.error("Unexpected error: Unable to get authenticated user after " + - "apparent successful login! Exception follows.", e); + } catch (IOException ex) { + LOG.error("Unexpected error: Unable to get authenticated user after " + + "apparent successful login! Exception follows.", ex); return false; } } @@ -592,9 +605,8 @@ private boolean authenticate() { LOG.info(" Superuser auth: {}", superUser.getAuthenticationMethod()); LOG.info(" Superuser name: {}", superUser.getUserName()); LOG.info(" Superuser using keytab: {}", superUser.isFromKeytab()); - } catch (IOException e) { - LOG.error("Unexpected error: unknown superuser impersonating proxy.", - e); + } catch (IOException ex) { + LOG.error("Unexpected error: unknown superuser impersonating proxy.", ex); return false; } } @@ -608,7 +620,7 @@ private boolean authenticate() { } /** - * Append to bucket writer with timeout enforced + * Append to bucket writer with timeout enforced. */ private void appendBatch(final BucketWriter bucketWriter, final List events) throws IOException, InterruptedException { @@ -623,7 +635,7 @@ public Void call() throws Exception { } /** - * Flush bucket writer with timeout enforced + * Flush bucket writer with timeout enforced. */ private void flush(final BucketWriter bucketWriter) throws IOException, InterruptedException { @@ -638,7 +650,7 @@ public Void call() throws Exception { } /** - * Close bucket writer with timeout enforced + * Close bucket writer with timeout enforced. */ private void close(final BucketWriter bucketWriter) throws IOException, InterruptedException { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/admin/controller/CtlController.java b/server/node/src/main/java/org/kaaproject/kaa/server/admin/controller/CtlController.java index dcc460f2ff..820bf8b278 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/admin/controller/CtlController.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/admin/controller/CtlController.java @@ -22,7 +22,7 @@ import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; -import org.kaaproject.kaa.common.dto.ctl.CtlSchemaDto; +import org.kaaproject.kaa.common.dto.ctl.CTLSchemaDto; import org.kaaproject.kaa.common.dto.ctl.CTLSchemaExportMethod; import org.kaaproject.kaa.common.dto.ctl.CTLSchemaMetaInfoDto; import org.kaaproject.kaa.common.dto.file.FileData; @@ -76,7 +76,7 @@ public class CtlController extends AbstractAdminController { @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/saveSchema", params = {"body"}, method = RequestMethod.POST) @ResponseBody - public CtlSchemaDto saveCtlSchemaWithAppToken( + public CTLSchemaDto saveCtlSchemaWithAppToken( @ApiParam(name = "body", value = "The CTL schema structure", required = true) @RequestParam String body, @ApiParam(name = "tenantId", value = "A unique tenant identifier", required = false) @@ -156,7 +156,7 @@ public void deleteCtlSchemaByFqnVersionTenantIdAndApplicationToken( @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/getSchema", params = {"fqn", "version"}, method = RequestMethod.GET) @ResponseBody - public CtlSchemaDto getCtlSchemaByFqnVersionTenantIdAndApplicationToken( + public CTLSchemaDto getCtlSchemaByFqnVersionTenantIdAndApplicationToken( @ApiParam(name = "fqn", value = "The fully qualified name of the CTL schema", required = true) @RequestParam String fqn, @@ -192,7 +192,7 @@ public CtlSchemaDto getCtlSchemaByFqnVersionTenantIdAndApplicationToken( @ApiResponse(code = 500, message = "An unexpected error occurred on the server side")}) @RequestMapping(value = "CTL/getSchemaById", params = {"id"}, method = RequestMethod.GET) @ResponseBody - public CtlSchemaDto getCtlSchemaById( + public CTLSchemaDto getCtlSchemaById( @ApiParam(name = "id", value = "A unique CTL schema identifier", required = true) @RequestParam String id) throws KaaAdminServiceException { return ctlService.getCtlSchemaById(id); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/initialization/BootstrapInitializationService.java b/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/initialization/BootstrapInitializationService.java index dac611d27d..de3803b719 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/initialization/BootstrapInitializationService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/initialization/BootstrapInitializationService.java @@ -89,7 +89,7 @@ public void start() { bootstrapTransportService.lookupAndInit(); if (getNodeConfig().isZkEnabled()) { - startZK(); + startZk(); operationsServerListService.init(bootstrapNode); bootstrapTransportService.addListener(new TransportUpdateListener() { @@ -99,8 +99,8 @@ public void onTransportsStarted(List mdList) { info.setTransports(mdList); try { bootstrapNode.updateNodeData(info); - } catch (IOException e) { - LOG.error("Failed to update bootstrap node info", e); + } catch (IOException ex) { + LOG.error("Failed to update bootstrap node info", ex); } } @@ -110,8 +110,8 @@ public void onTransportsStarted(List mdList) { bootstrapTransportService.start(); LOG.info("Bootstrap Service Started."); - } catch (Exception e) { - LOG.error("Error starting Bootstrap Service", e); + } catch (Exception ex) { + LOG.error("Error starting Bootstrap Service", ex); } } @@ -127,7 +127,7 @@ public void stop() { LOG.trace("Stopping Bootstrap Service..." + propertiesToString()); if (getNodeConfig().isZkEnabled()) { - stopZK(); + stopZk(); } if (bootstrapTransportService != null) { @@ -141,15 +141,19 @@ public void stop() { * * @throws Exception in case of error */ - private void startZK() throws Exception { // NOSONAR + private void startZk() throws Exception { // NOSONAR if (getNodeConfig().isZkEnabled()) { - LOG.info("Bootstrap service starting ZooKepper connection to {}", getNodeConfig().getZkHostPortList()); + LOG.info("Bootstrap service starting ZooKepper connection to {}", + getNodeConfig().getZkHostPortList()); BootstrapNodeInfo nodeInfo = new BootstrapNodeInfo(); ByteBuffer keyData = ByteBuffer.wrap(bootstrapKeyStoreService.getPublicKey().getEncoded()); - LOG.trace("Bootstrap service: registering in ZK: thriftHost {}; thriftPort {}; nettyHost {}; nettyPort {}", getNodeConfig().getThriftHost(), + LOG.trace("Bootstrap service: registering in ZK: thriftHost {}; " + + "thriftPort {}; nettyHost {}; nettyPort {}", + getNodeConfig().getThriftHost(), getNodeConfig().getThriftPort()); - nodeInfo.setConnectionInfo(new ConnectionInfo(getNodeConfig().getThriftHost(), getNodeConfig().getThriftPort(), keyData)); - nodeInfo.setTransports(new ArrayList()); + nodeInfo.setConnectionInfo(new ConnectionInfo( + getNodeConfig().getThriftHost(), getNodeConfig().getThriftPort(), keyData)); + nodeInfo.setTransports(new ArrayList<>()); nodeInfo.setTimeStarted(System.currentTimeMillis()); bootstrapNode = new BootstrapNode(nodeInfo, zkClient); if (bootstrapNode != null) { @@ -161,13 +165,13 @@ private void startZK() throws Exception { // NOSONAR /** * Stop zk. */ - private void stopZK() { + private void stopZk() { try { if (bootstrapNode != null) { bootstrapNode.close(); } - } catch (IOException e) { - LOG.warn("Exception when closing ZK node", e); + } catch (IOException ex) { + LOG.warn("Exception when closing ZK node", ex); } finally { bootstrapNode = null; } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/security/BootstrapFileKeyStoreService.java b/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/security/BootstrapFileKeyStoreService.java index 279b6c4d2c..8aac2a7e2c 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/security/BootstrapFileKeyStoreService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/security/BootstrapFileKeyStoreService.java @@ -59,23 +59,24 @@ public BootstrapFileKeyStoreService() { public void loadKeys() { privateKeyLocation = Environment.getServerHomeDir() + File.separator + privateKeyLocation; publicKeyLocation = Environment.getServerHomeDir() + File.separator + publicKeyLocation; - LOG.debug("Loading private key from {}; public key from {}", privateKeyLocation, publicKeyLocation); - File f = new File(privateKeyLocation); - if (f.exists()) { + LOG.debug("Loading private key from {}; public key from {}", + privateKeyLocation, publicKeyLocation); + File file = new File(privateKeyLocation); + 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(publicKeyLocation); - if (f.exists()) { + file = new File(publicKeyLocation); + 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) { @@ -109,7 +110,8 @@ public PublicKey getPublicKey() { * @return the key pair */ private KeyPair generateKeyPair(String privateKeyLocation, String publicKeyLocation) { - LOG.debug("Generating key pair (private at {}; public at {})", privateKeyLocation, publicKeyLocation); + LOG.debug("Generating key pair (private at {}; public at {})", + privateKeyLocation, publicKeyLocation); return KeyUtil.generateKeyPair(privateKeyLocation, publicKeyLocation); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/thrift/BootstrapThriftServiceImpl.java b/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/thrift/BootstrapThriftServiceImpl.java index 89ae2ef258..459354d9a4 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/thrift/BootstrapThriftServiceImpl.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/thrift/BootstrapThriftServiceImpl.java @@ -39,16 +39,19 @@ public class BootstrapThriftServiceImpl implements private static final Logger LOG = LoggerFactory.getLogger(BootstrapThriftServiceImpl.class); /** - * Thrift method to receive new list of Operations servers + * Thrift method to receive new list of Operations servers. * * @param operationsServersList the list of type ThriftOperationsServer */ /* (non-Javadoc) - * @see org.kaaproject.kaa.server.common.thrift.gen.bootstrap.BootstrapThriftService.Iface#onOperationsServerListUpdate(java.util.List) + * @see org.kaaproject.kaa.server.common.thrift.gen.bootstrap + * .BootstrapThriftService.Iface#onOperationsServerListUpdate(java.util.List) */ @Override - public void onOperationsServerListUpdate(List operationsServersList) throws TException { - LOG.info("Operations server list update recived: now {} servers online:", operationsServersList.size()); + public void onOperationsServerListUpdate(List operationsServersList) + throws TException { + LOG.info("Operations server list update recived: now {} servers online:", + operationsServersList.size()); //TODO: add usage of ops list priority in future releases. } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/transport/BootstrapTransportService.java b/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/transport/BootstrapTransportService.java index 58f2a7c371..e129a0cd26 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/transport/BootstrapTransportService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/bootstrap/service/transport/BootstrapTransportService.java @@ -53,12 +53,14 @@ import java.util.concurrent.Executors; /** - * Responsible for initialization and management of transport instances + * Responsible for initialization and management of transport instances. * * @author Andrew Shvayka */ @Service -public class BootstrapTransportService extends AbstractTransportService implements TransportService { +public class BootstrapTransportService + extends AbstractTransportService + implements TransportService { /** * Constant LOG. @@ -103,10 +105,17 @@ protected Properties getServiceProperties() { @Override public void lookupAndInit() { 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 message handler with {} worker threads", threadPoolSize); - handler = new BootstrapMessageHandler(operationsServerListService, Executors.newFixedThreadPool(threadPoolSize), platformProtocols, - new KeyPair(bootstrapKeyStoreService.getPublicKey(), bootstrapKeyStoreService.getPrivateKey()), supportUnencryptedConnection); + handler = new BootstrapMessageHandler( + operationsServerListService, + Executors.newFixedThreadPool(threadPoolSize), + platformProtocols, + new KeyPair( + bootstrapKeyStoreService.getPublicKey(), + bootstrapKeyStoreService.getPrivateKey()), + supportUnencryptedConnection); super.lookupAndInit(); } @@ -128,7 +137,8 @@ public void stop() { public static class BootstrapMessageHandler implements MessageHandler { - private static final ThreadLocal> platformEncDecMap = new ThreadLocal<>(); //NOSONAR + private static final ThreadLocal> platformEncDecMap = + new ThreadLocal<>(); //NOSONAR private static final ThreadLocal crypt = new ThreadLocal<>(); //NOSONAR private final ExecutorService executor; private final Set platformProtocols; @@ -136,8 +146,11 @@ public static class BootstrapMessageHandler implements MessageHandler { private final boolean supportUnencryptedConnection; private final OperationsServerListService opsListService; - public BootstrapMessageHandler(OperationsServerListService opsListService, ExecutorService executor, Set platformProtocols, - KeyPair keyPair, boolean supportUnencryptedConnection) { + public BootstrapMessageHandler(OperationsServerListService opsListService, + ExecutorService executor, + Set platformProtocols, + KeyPair keyPair, + boolean supportUnencryptedConnection) { super(); this.opsListService = opsListService; this.executor = executor; @@ -164,7 +177,8 @@ public void run() { LOG.trace("Processing request {}", request); BootstrapClientSync bsRequest = request.getBootstrapSync(); Set transports = opsListService.filter(bsRequest.getKeys()); - BootstrapServerSync bsResponse = new BootstrapServerSync(bsRequest.getRequestId(), transports); + BootstrapServerSync bsResponse = new BootstrapServerSync( + bsRequest.getRequestId(), transports); ServerSync response = new ServerSync(); response.setRequestId(request.getRequestId()); response.setStatus(SyncStatus.SUCCESS); @@ -172,16 +186,19 @@ public void run() { LOG.trace("Response {}", response); encodeAndForward(message, crypt, platformEncDecMap, response); LOG.trace("Response forwarded to specific transport {}", response); - } catch (Exception e) { - processErrors(message.getChannelContext(), message.getErrorBuilder(), e); + } catch (Exception ex) { + processErrors(message.getChannelContext(), message.getErrorBuilder(), ex); } } - private void encodeAndForward(final SessionInitMessage message, MessageEncoderDecoder crypt, - Map platformEncDecMap, ServerSync response) throws PlatformEncDecException, - GeneralSecurityException { + private void encodeAndForward(final SessionInitMessage message, + MessageEncoderDecoder crypt, + Map platformEncDecMap, + ServerSync response) + throws PlatformEncDecException, GeneralSecurityException { MessageBuilder converter = message.getMessageBuilder(); - byte[] responseData = encodePlatformLevelData(platformEncDecMap, message.getPlatformId(), response); + byte[] responseData = encodePlatformLevelData( + platformEncDecMap, message.getPlatformId(), response); Object[] objects; if (message.isEncrypted()) { byte[] responseSignature = crypt.sign(responseData); @@ -203,28 +220,32 @@ private void encodeAndForward(final SessionInitMessage message, MessageEncoderDe } } - private void processErrors(ChannelContext ctx, ErrorBuilder converter, Exception e) { - LOG.trace("Message processing failed", e); - Object[] responses = converter.build(e); + private void processErrors(ChannelContext ctx, ErrorBuilder converter, Exception ex) { + LOG.trace("Message processing failed", ex); + Object[] responses = converter.build(ex); if (responses != null && responses.length > 0) { for (Object response : responses) { ctx.writeAndFlush(response); } } else { - ctx.fireExceptionCaught(e); + ctx.fireExceptionCaught(ex); } } - private ClientSync decodeRequest(SessionInitMessage message, MessageEncoderDecoder crypt, - Map platformEncDecMap) throws GeneralSecurityException, PlatformEncDecException { + private ClientSync decodeRequest(SessionInitMessage message, + MessageEncoderDecoder crypt, + Map platformEncDecMap) + throws GeneralSecurityException, PlatformEncDecException { ClientSync syncRequest = null; if (message.isEncrypted()) { syncRequest = decodeEncryptedRequest(message, crypt, platformEncDecMap); } else if (supportUnencryptedConnection) { syncRequest = decodeUnencryptedRequest(message, platformEncDecMap); } else { - LOG.warn("Received unencrypted init message, but unencrypted connection forbidden by configuration."); - throw new GeneralSecurityException("Unencrypted connection forbidden by configuration."); + LOG.warn("Received unencrypted init message, but unencrypted connection " + + "forbidden by configuration."); + throw new GeneralSecurityException( + "Unencrypted connection forbidden by configuration."); } if (syncRequest.getBootstrapSync() == null) { throw new IllegalArgumentException("Bootstrap sync message is missing"); @@ -232,42 +253,54 @@ private ClientSync decodeRequest(SessionInitMessage message, MessageEncoderDecod return syncRequest; } - private ClientSync decodeEncryptedRequest(SessionInitMessage message, MessageEncoderDecoder crypt, - Map platformEncDecMap) throws GeneralSecurityException, PlatformEncDecException { - byte[] requestRaw = crypt.decodeData(message.getEncodedMessageData(), message.getEncodedSessionKey()); + private ClientSync decodeEncryptedRequest(SessionInitMessage message, + MessageEncoderDecoder crypt, + Map platformEncDecMap) + throws GeneralSecurityException, PlatformEncDecException { + byte[] requestRaw = crypt.decodeData( + message.getEncodedMessageData(), message.getEncodedSessionKey()); LOG.trace("Request data decrypted"); - ClientSync request = decodePlatformLevelData(platformEncDecMap, message.getPlatformId(), requestRaw); + ClientSync request = decodePlatformLevelData( + platformEncDecMap, message.getPlatformId(), requestRaw); LOG.trace("Request data deserialized"); return request; } - private ClientSync decodeUnencryptedRequest(SessionInitMessage message, Map platformEncDecMap) + private ClientSync decodeUnencryptedRequest(SessionInitMessage message, + Map platformEncDecMap) throws GeneralSecurityException, PlatformEncDecException { byte[] requestRaw = message.getEncodedMessageData(); LOG.trace("Try to convert raw data to SynRequest object"); - ClientSync request = decodePlatformLevelData(platformEncDecMap, message.getPlatformId(), requestRaw); + ClientSync request = decodePlatformLevelData( + platformEncDecMap, message.getPlatformId(), requestRaw); LOG.trace("Request data deserialized"); return request; } - private byte[] encodePlatformLevelData(Map platformEncDecMap, int platformID, ServerSync sync) + private byte[] encodePlatformLevelData(Map platformEncDecMap, + int platformID, + ServerSync sync) throws PlatformEncDecException { PlatformEncDec encDec = platformEncDecMap.get(platformID); if (encDec != null) { return platformEncDecMap.get(platformID).encode(sync); } else { - throw new PlatformEncDecException(MessageFormat.format("Encoder for platform protocol [{0}] is not defined", + throw new PlatformEncDecException( + MessageFormat.format("Encoder for platform protocol [{0}] is not defined", platformID)); } } - private ClientSync decodePlatformLevelData(Map platformEncDecMap, Integer platformID, - byte[] requestRaw) throws PlatformEncDecException { + private ClientSync decodePlatformLevelData(Map platformEncDecMap, + Integer platformID, + byte[] requestRaw) + throws PlatformEncDecException { PlatformEncDec encDec = platformEncDecMap.get(platformID); if (encDec != null) { return platformEncDecMap.get(platformID).decode(requestRaw); } else { - throw new PlatformEncDecException(MessageFormat.format("Decoder for platform protocol [{0}] is not defined", + throw new PlatformEncDecException + (MessageFormat.format("Decoder for platform protocol [{0}] is not defined", platformID)); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/DefaultOperationsService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/DefaultOperationsService.java index e41bc2aa1d..eae795567e 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/DefaultOperationsService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/DefaultOperationsService.java @@ -16,7 +16,6 @@ package org.kaaproject.kaa.server.operations.service; -import org.kaaproject.kaa.common.dto.EndpointGroupStateDto; import org.kaaproject.kaa.common.dto.EndpointProfileDto; import org.kaaproject.kaa.common.dto.EndpointUserConfigurationDto; import org.kaaproject.kaa.common.dto.NotificationDto; @@ -123,12 +122,13 @@ public class DefaultOperationsService implements OperationsService { * @param notificationResponse the notification response * @return the notification sync response */ - private static NotificationServerSync buildNotificationSyncResponse(GetNotificationResponse notificationResponse) { + private static NotificationServerSync buildNotificationSyncResponse( + GetNotificationResponse notificationResponse) { NotificationServerSync response = new NotificationServerSync(); response.setResponseStatus(SyncResponseStatus.NO_DELTA); if (notificationResponse.getNotifications() != null) { - List notifications = new ArrayList(); + List notifications = new ArrayList<>(); for (NotificationDto notificationDto : notificationResponse.getNotifications()) { notifications.add(convertNotification(notificationDto)); } @@ -199,22 +199,24 @@ private static Notification convertNotification(NotificationDto notificationDto) * @return the conf sync response * @throws GetDeltaException the get delta exception */ - private static ConfigurationServerSync buildConfSyncResponse(GetDeltaResponse deltaResponse) throws GetDeltaException { + private static ConfigurationServerSync buildConfSyncResponse(GetDeltaResponse deltaResponse) + throws GetDeltaException { ConfigurationServerSync response = new ConfigurationServerSync(); if (deltaResponse.getDelta() != null) { try { response.setConfDeltaBody(ByteBuffer.wrap(deltaResponse.getDelta().getData())); - } catch (IOException e) { - LOG.error("conf delta invalid: {}", e); - throw new GetDeltaException(e); + } catch (IOException ex) { + LOG.error("conf delta invalid: {}", ex); + throw new GetDeltaException(ex); } } if (deltaResponse.getConfSchema() != null) { try { - response.setConfSchemaBody(ByteBuffer.wrap(deltaResponse.getConfSchema().getBytes("UTF-8"))); - } catch (UnsupportedEncodingException e) { - LOG.error("conf schema invalid: {}", e); - throw new GetDeltaException(e); + response.setConfSchemaBody( + ByteBuffer.wrap(deltaResponse.getConfSchema().getBytes("UTF-8"))); + } catch (UnsupportedEncodingException ex) { + LOG.error("conf schema invalid: {}", ex); + throw new GetDeltaException(ex); } } switch (deltaResponse.getResponseType()) { @@ -259,11 +261,15 @@ public SyncContext syncClientProfile(SyncContext context, ProfileClientSync prof if (profileSyncRequest != null) { ProfileServerSync profileSyncResponse; if (profileSyncRequest.getEndpointPublicKey() != null) { - LOG.debug("[{}][{}] registration of endpoint started.", context.getEndpointKey(), context.getRequestHash()); - profile = registerEndpoint(context.getEndpointKey(), context.getRequestHash(), metaData, profileSyncRequest); + LOG.debug("[{}][{}] registration of endpoint started.", + context.getEndpointKey(), context.getRequestHash()); + profile = registerEndpoint( + context.getEndpointKey(), context.getRequestHash(), metaData, profileSyncRequest); } else { - LOG.debug("[{}][{}] update of endpoint profile started.", context.getEndpointKey(), context.getRequestHash()); - profile = updateEndpoint(context.getEndpointKey(), context.getRequestHash(), metaData, profileSyncRequest); + LOG.debug("[{}][{}] update of endpoint profile started.", + context.getEndpointKey(), context.getRequestHash()); + profile = updateEndpoint + (context.getEndpointKey(), context.getRequestHash(), metaData, profileSyncRequest); } profileSyncResponse = new ProfileServerSync(SyncResponseStatus.DELTA); metaData.setProfileHash(ByteBuffer.wrap(profile.getProfileHash())); @@ -272,9 +278,11 @@ public SyncContext syncClientProfile(SyncContext context, ProfileClientSync prof if (profile == null) { LOG.debug("[{}][{}] fetching profile.", context.getEndpointKey(), context.getRequestHash()); - EndpointObjectHash endpointHash = EndpointObjectHash.fromBytes(metaData.getEndpointPublicKeyHash().array()); + EndpointObjectHash endpointHash = EndpointObjectHash.fromBytes( + metaData.getEndpointPublicKeyHash().array()); profile = profileService.getProfile(endpointHash); - LOG.trace("[{}][{}] fetched profile {}.", context.getEndpointKey(), context.getRequestHash(), profile); + LOG.trace("[{}][{}] fetched profile {}.", + context.getEndpointKey(), context.getRequestHash(), profile); } if (!Arrays.equals(profile.getProfileHash(), toByteArray(metaData.getProfileHash()))) { @@ -288,7 +296,8 @@ public SyncContext syncClientProfile(SyncContext context, ProfileClientSync prof context.setStatus(SyncStatus.PROFILE_RESYNC); } - profile = syncProfileState(metaData.getApplicationToken(), context.getEndpointKey(), profile, false); + profile = syncProfileState( + metaData.getApplicationToken(), context.getEndpointKey(), profile, false); context.setEndpointProfile(profile); @@ -296,7 +305,9 @@ public SyncContext syncClientProfile(SyncContext context, ProfileClientSync prof } @Override - public EndpointProfileDto syncServerProfile(String appToken, String endpointKey, EndpointObjectHash key) { + public EndpointProfileDto syncServerProfile(String appToken, + String endpointKey, + EndpointObjectHash key) { EndpointProfileDto profile = refreshServerEndpointProfile(key); profile.setGroupState(new ArrayList<>()); profile = syncProfileState(appToken, endpointKey, profile, false); @@ -304,10 +315,15 @@ public EndpointProfileDto syncServerProfile(String appToken, String endpointKey, } @Override - public SyncContext processEndpointAttachDetachRequests(SyncContext context, UserClientSync request) { + public SyncContext processEndpointAttachDetachRequests(SyncContext context, + UserClientSync request) { if (request != null) { - LOG.trace("[{}][{}] procesing user sync request {}.", context.getEndpointKey(), context.getRequestHash(), request); - UserServerSync userSyncResponse = processUserSyncRequest(context.getEndpointKey(), context.getRequestHash(), request, + LOG.trace("[{}][{}] procesing user sync request {}.", + context.getEndpointKey(), context.getRequestHash(), request); + UserServerSync userSyncResponse = processUserSyncRequest( + context.getEndpointKey(), + context.getRequestHash(), + request, context.getEndpointProfile()); context.setUserSyncResponse(userSyncResponse); } @@ -318,38 +334,44 @@ public SyncContext processEndpointAttachDetachRequests(SyncContext context, User public SyncContext processEventListenerRequests(SyncContext context, EventClientSync request) { if (request != null) { ClientSyncMetaData metaData = context.getMetaData(); - LOG.trace("[{}][{}] procesing event sync request {}.", context.getEndpointKey(), context.getRequestHash(), request); - EventServerSync eventSyncResponse = processEventSyncResponse(context.getEndpointKey(), context.getRequestHash(), + LOG.trace("[{}][{}] procesing event sync request {}.", + context.getEndpointKey(), context.getRequestHash(), request); + EventServerSync eventSyncResponse = processEventSyncResponse( + context.getEndpointKey(), context.getRequestHash(), metaData.getApplicationToken(), request, context.getEndpointProfile()); context.setEventSyncResponse(eventSyncResponse); } return context; } - private EndpointProfileDto syncProfileState(String appToken, String endpointId, EndpointProfileDto endpointProfile, boolean userConfigurationChanged) { + private EndpointProfileDto syncProfileState(String appToken, String endpointId, + EndpointProfileDto endpointProfile, + boolean userConfigurationChanged) { LOG.debug("[{}][{}] going to sync endpoint group states", appToken, endpointId); - Function> updateFunction = profile -> { - AppSeqNumber appSeqNumber = cacheService.getAppSeqNumber(appToken); - int curAppSeqNumber = appSeqNumber.getSeqNumber(); - HistoryDelta historyDelta = fetchHistory(endpointId, appToken, profile, curAppSeqNumber); - profile.setGroupState(historyDelta.getEndpointGroupStates()); - profile.setSequenceNumber(curAppSeqNumber); - if (historyDelta.isConfigurationChanged() || userConfigurationChanged) { - LOG.debug("[{}][{}] configuration change detected", appToken, endpointId); - try { - syncEndpointConfiguration(appToken, endpointId, profile); - } catch (GetDeltaException e) { - // TODO: Figure out how to act in case of failover here. - LOG.error("[{}][{}] Failed to sync endpoint configuration {}", appToken, endpointId, e); - } - } - if (historyDelta.isTopicListChanged()) { - LOG.debug("[{}][{}] topic list change detected", appToken, endpointId); - syncTopicList(appToken, endpointId, profile); - } - return new Pair<>(profile, historyDelta); - }; + Function> updateFunction = + profile -> { + AppSeqNumber appSeqNumber = cacheService.getAppSeqNumber(appToken); + int curAppSeqNumber = appSeqNumber.getSeqNumber(); + HistoryDelta historyDelta = fetchHistory(endpointId, appToken, profile, curAppSeqNumber); + profile.setGroupState(historyDelta.getEndpointGroupStates()); + profile.setSequenceNumber(curAppSeqNumber); + if (historyDelta.isConfigurationChanged() || userConfigurationChanged) { + LOG.debug("[{}][{}] configuration change detected", appToken, endpointId); + try { + syncEndpointConfiguration(appToken, endpointId, profile); + } catch (GetDeltaException ex) { + // TODO: Figure out how to act in case of failover here. + LOG.error("[{}][{}] Failed to sync endpoint configuration {}", + appToken, endpointId, ex); + } + } + if (historyDelta.isTopicListChanged()) { + LOG.debug("[{}][{}] topic list change detected", appToken, endpointId); + syncTopicList(appToken, endpointId, profile); + } + return new Pair<>(profile, historyDelta); + }; Pair result = updateFunction.apply(endpointProfile); endpointProfile = result.getV1(); @@ -357,22 +379,27 @@ private EndpointProfileDto syncProfileState(String appToken, String endpointId, if (historyDelta.isSmthChanged() || userConfigurationChanged) { LOG.debug("[{}][{}] going to save new profile", appToken, endpointId); - endpointProfile = profileService.updateProfile(endpointProfile, (storedProfile, newProfile) -> { - if (userConfigurationChanged) { - storedProfile.setUserConfigurationHash(newProfile.getUserConfigurationHash()); - } - storedProfile.setGroupState(new ArrayList()); - return updateFunction.apply(storedProfile).getV1(); - }); + endpointProfile = profileService.updateProfile(endpointProfile, + (storedProfile, newProfile) -> { + if (userConfigurationChanged) { + storedProfile.setUserConfigurationHash(newProfile.getUserConfigurationHash()); + } + storedProfile.setGroupState(new ArrayList<>()); + return updateFunction.apply(storedProfile).getV1(); + }); } return endpointProfile; } - private void syncEndpointConfiguration(String appToken, String endpointId, EndpointProfileDto profile) throws GetDeltaException { - ConfigurationCacheEntry configurationCache = deltaService.getConfiguration(appToken, endpointId, profile); + private void syncEndpointConfiguration(String appToken, + String endpointId, + EndpointProfileDto profile) throws GetDeltaException { + ConfigurationCacheEntry configurationCache = deltaService.getConfiguration( + appToken, endpointId, profile); byte[] configurationHash = configurationCache.getHash().getData(); if (LOG.isTraceEnabled()) { - LOG.trace("[{}][{}] Result configuration hash is {}", appToken, endpointId, Arrays.toString(configurationHash)); + LOG.trace("[{}][{}] Result configuration hash is {}", + appToken, endpointId, Arrays.toString(configurationHash)); } profile.setConfigurationHash(configurationHash); if (configurationCache.getUserConfigurationHash() != null) { @@ -383,7 +410,8 @@ private void syncEndpointConfiguration(String appToken, String endpointId, Endpo } private void syncTopicList(String appToken, String endpointId, EndpointProfileDto profile) { - TopicListCacheEntry topicListCache = notificationDeltaService.getTopicListHash(appToken, endpointId, profile); + TopicListCacheEntry topicListCache = notificationDeltaService.getTopicListHash( + appToken, endpointId, profile); if (LOG.isTraceEnabled()) { LOG.trace("[{}][{}] Result topic hash is {}", appToken, endpointId, topicListCache); } @@ -392,9 +420,11 @@ private void syncTopicList(String appToken, String endpointId, EndpointProfileDt } @Override - public SyncContext syncConfiguration(SyncContext context, ConfigurationClientSync request) throws GetDeltaException { + public SyncContext syncConfiguration(SyncContext context, ConfigurationClientSync request) + throws GetDeltaException { if (request != null) { - GetDeltaResponse confResponse = calculateConfigurationDelta(context.getMetaData().getApplicationToken(), request, context); + GetDeltaResponse confResponse = calculateConfigurationDelta( + context.getMetaData().getApplicationToken(), request, context); ConfigurationServerSync confSyncResponse = buildConfSyncResponse(confResponse); context.setConfigurationSyncResponse(confSyncResponse); } @@ -410,13 +440,16 @@ public SyncContext syncUserConfigurationHash(SyncContext context, byte[] ucfHash } @Override - public SyncContext syncUseConfigurationRawSchema(SyncContext context, boolean useConfigurationRawSchema) { + public SyncContext syncUseConfigurationRawSchema(SyncContext context, + boolean useConfigurationRawSchema) { EndpointProfileDto profile = context.getEndpointProfile(); if (profile.isUseConfigurationRawSchema() != useConfigurationRawSchema) { ClientSyncMetaData metaData = context.getMetaData(); - EndpointObjectHash endpointKeyHash = EndpointObjectHash.fromBytes(toByteArray(metaData.getEndpointPublicKeyHash())); + EndpointObjectHash endpointKeyHash = EndpointObjectHash.fromBytes( + toByteArray(metaData.getEndpointPublicKeyHash())); profile = profileService.updateProfile(metaData, endpointKeyHash, useConfigurationRawSchema); - profile = syncProfileState(metaData.getApplicationToken(), context.getEndpointKey(), profile, false); + profile = syncProfileState( + metaData.getApplicationToken(), context.getEndpointKey(), profile, false); context.setEndpointProfile(profile); } return context; @@ -425,7 +458,8 @@ public SyncContext syncUseConfigurationRawSchema(SyncContext context, boolean us @Override public SyncContext syncNotification(SyncContext context, NotificationClientSync request) { if (request != null) { - GetNotificationResponse notificationResponse = calculateNotificationDelta(context.getMetaData().getApplicationToken(), request, + GetNotificationResponse notificationResponse = calculateNotificationDelta( + context.getMetaData().getApplicationToken(), request, context); context.setSubscriptionStates(notificationResponse.getSubscriptionStates()); NotificationServerSync nfSyncResponse = buildNotificationSyncResponse(notificationResponse); @@ -437,9 +471,10 @@ public SyncContext syncNotification(SyncContext context, NotificationClientSync profile.setSubscriptions(new ArrayList<>(notificationResponse.getSubscriptionSet())); return profile; }; - context.setEndpointProfile(profileService.updateProfile(updateFunction.apply(profileDto), (storedProfile, newProfile) -> { - return updateFunction.apply(storedProfile); - })); + context.setEndpointProfile(profileService.updateProfile( + updateFunction.apply(profileDto), (storedProfile, newProfile) -> { + return updateFunction.apply(storedProfile); + })); } } return context; @@ -452,12 +487,12 @@ public SyncContext syncNotification(SyncContext context, NotificationClientSync public SyncContext syncProfileServerHash(SyncContext context) { EndpointProfileDto profile = context.getEndpointProfile(); if (!operationServerHash.equals(profile.getServerHash())) { - LOG.debug("[{}] Operations server hash changed from {} to {}", context.getEndpointKey(), profile.getServerHash(), + LOG.debug("[{}] Operations server hash changed from {} to {}", + context.getEndpointKey(), profile.getServerHash(), operationServerHash); profile.setServerHash(operationServerHash); - context.setEndpointProfile(profileService.updateProfile(profile, (storedProfile, newProfile) -> { - return storedProfile; - })); + context.setEndpointProfile(profileService.updateProfile(profile, + (storedProfile, newProfile) -> storedProfile)); } return context; } @@ -467,7 +502,8 @@ public byte[] fetchUcfHash(String appToken, EndpointProfileDto profile) { if (profile.getEndpointUserId() == null || profile.getEndpointUserId().isEmpty()) { return null; } - EndpointUserConfigurationDto ucfDto = userConfigurationService.findUserConfigurationByUserIdAndAppTokenAndSchemaVersion( + EndpointUserConfigurationDto ucfDto = + userConfigurationService.findUserConfigurationByUserIdAndAppTokenAndSchemaVersion( profile.getEndpointUserId(), appToken, profile.getConfigurationVersion()); if (ucfDto != null) { return EndpointObjectHash.fromString(ucfDto.getBody()).getData(); @@ -475,29 +511,46 @@ public byte[] fetchUcfHash(String appToken, EndpointProfileDto profile) { return null; } - private EndpointProfileDto registerEndpoint(String endpointId, int requestHash, ClientSyncMetaData metaData, ProfileClientSync request) { + private EndpointProfileDto registerEndpoint(String endpointId, + int requestHash, + ClientSyncMetaData metaData, + ProfileClientSync request) { LOG.debug("[{}][{}] register endpoint. request: {}", endpointId, requestHash, request); byte[] endpointKey = toByteArray(request.getEndpointPublicKey()); byte[] profileBody = toByteArray(request.getProfileBody()); - RegisterProfileRequest registerProfileRequest = new RegisterProfileRequest(metaData.getApplicationToken(), endpointKey, + RegisterProfileRequest registerProfileRequest = new RegisterProfileRequest( + metaData.getApplicationToken(), endpointKey, metaData.getSdkToken(), profileBody, request.getEndpointAccessToken()); EndpointProfileDto endpointProfile = profileService.registerProfile(registerProfileRequest); - LOG.debug("profile registered. id: {}, endpointKeyHash: {}", endpointProfile.getId(), endpointProfile.getEndpointKeyHash()); + LOG.debug("profile registered. id: {}, endpointKeyHash: {}", + endpointProfile.getId(), endpointProfile.getEndpointKeyHash()); return endpointProfile; } - private EndpointProfileDto updateEndpoint(String endpointId, int requestHash, ClientSyncMetaData metaData, ProfileClientSync request) { + private EndpointProfileDto updateEndpoint(String endpointId, + int requestHash, + ClientSyncMetaData metaData, + ProfileClientSync request) { LOG.debug("[{}][{}] update endpoint. request: {}", endpointId, requestHash, request); - EndpointObjectHash endpointKeyHash = EndpointObjectHash.fromBytes(toByteArray(metaData.getEndpointPublicKeyHash())); - UpdateProfileRequest updateRequest = new UpdateProfileRequest(metaData.getApplicationToken(), endpointKeyHash, - request.getEndpointAccessToken(), request.getProfileBody().array(), metaData.getSdkToken()); + EndpointObjectHash endpointKeyHash = EndpointObjectHash.fromBytes( + toByteArray(metaData.getEndpointPublicKeyHash())); + UpdateProfileRequest updateRequest = new UpdateProfileRequest( + metaData.getApplicationToken(), + endpointKeyHash, + request.getEndpointAccessToken(), + request.getProfileBody().array(), + metaData.getSdkToken()); EndpointProfileDto endpointProfile = profileService.updateProfile(updateRequest); - LOG.debug("profile updated. id: {}, endpointKeyHash: {}", endpointProfile.getId(), endpointProfile.getEndpointKeyHash()); + LOG.debug("profile updated. id: {}, endpointKeyHash: {}", + endpointProfile.getId(), endpointProfile.getEndpointKeyHash()); return endpointProfile; } - private EventServerSync processEventSyncResponse(String endpointId, int requestHash, String appToken, EventClientSync request, + private EventServerSync processEventSyncResponse(String endpointId, + int requestHash, + String appToken, + EventClientSync request, EndpointProfileDto profile) { EventServerSync response = new EventServerSync(); List requests = request.getEventListenersRequests(); @@ -506,7 +559,8 @@ private EventServerSync processEventSyncResponse(String endpointId, int requestH List responses = new ArrayList<>(requests.size()); for (EventListenersRequest elRequest : requests) { LOG.debug("[{}] processing event listener request {}", endpointId, request); - EventListenersResponse elResponse = endpointUserService.findListeners(profile, appToken, elRequest); + EventListenersResponse elResponse = endpointUserService.findListeners( + profile, appToken, elRequest); LOG.debug("[{}] event listener response {}", endpointId, response); responses.add(elResponse); } @@ -518,25 +572,34 @@ private EventServerSync processEventSyncResponse(String endpointId, int requestH return response; } - private UserServerSync processUserSyncRequest(String endpointId, int requestHash, UserClientSync request, EndpointProfileDto profile) { + private UserServerSync processUserSyncRequest(String endpointId, + int requestHash, + UserClientSync request, + EndpointProfileDto profile) { UserServerSync response = new UserServerSync(); if (request.getEndpointAttachRequests() != null) { - response.setEndpointAttachResponses(processEndpointAttachRequests(endpointId, requestHash, request, profile)); + response.setEndpointAttachResponses(processEndpointAttachRequests( + endpointId, requestHash, request, profile)); } if (request.getEndpointDetachRequests() != null) { - response.setEndpointDetachResponses(processEndpointDetachRequests(endpointId, requestHash, request, profile)); + response.setEndpointDetachResponses(processEndpointDetachRequests( + endpointId, requestHash, request, profile)); } return response; } - private List processEndpointAttachRequests(String endpointId, int requestHash, UserClientSync syncRequest, + private List processEndpointAttachRequests(String endpointId, + int requestHash, + UserClientSync syncRequest, EndpointProfileDto profile) { List requests = syncRequest.getEndpointAttachRequests(); if (requests != null && !requests.isEmpty()) { - LOG.debug("[{}][{}] processing {} endpoint attach requests", endpointId, requestHash, requests.size()); + LOG.debug("[{}][{}] processing {} endpoint attach requests", + endpointId, requestHash, requests.size()); List responses = new ArrayList<>(requests.size()); for (EndpointAttachRequest request : syncRequest.getEndpointAttachRequests()) { - LOG.debug("[{}][{}] processing endpoint attach request {}", endpointId, requestHash, request); + LOG.debug("[{}][{}] processing endpoint attach request {}", + endpointId, requestHash, request); EndpointAttachResponse response = endpointUserService.attachEndpoint(profile, request); LOG.debug("[{}][{}] endpoint attach response {}", endpointId, requestHash, response); responses.add(response); @@ -547,7 +610,9 @@ private List processEndpointAttachRequests(String endpoi } } - private List processEndpointDetachRequests(String endpointId, int requestHash, UserClientSync syncRequest, + private List processEndpointDetachRequests(String endpointId, + int requestHash, + UserClientSync syncRequest, EndpointProfileDto profile) { List requests = syncRequest.getEndpointDetachRequests(); if (requests != null && !requests.isEmpty()) { @@ -568,14 +633,20 @@ private List processEndpointDetachRequests(String endpoi /** * Calculate notification delta. * + * @param appToken application token + * @param context context * @param syncRequest the sync request - * @param profile the profile - * @param historyDelta the history delta * @return the gets the notification response */ - private GetNotificationResponse calculateNotificationDelta(String appToken, NotificationClientSync syncRequest, SyncContext context) { - GetNotificationRequest request = new GetNotificationRequest(syncRequest.getTopicListHash(), context.getEndpointProfile(), - syncRequest.getSubscriptionCommands(), syncRequest.getAcceptedUnicastNotifications(), syncRequest.getTopicStates()); + private GetNotificationResponse calculateNotificationDelta(String appToken, + NotificationClientSync syncRequest, + SyncContext context) { + GetNotificationRequest request = new GetNotificationRequest( + syncRequest.getTopicListHash(), + context.getEndpointProfile(), + syncRequest.getSubscriptionCommands(), + syncRequest.getAcceptedUnicastNotifications(), + syncRequest.getTopicStates()); return notificationDeltaService.getNotificationDelta(request); } @@ -588,11 +659,14 @@ private GetNotificationResponse calculateNotificationDelta(String appToken, Noti * @return the gets the delta response * @throws GetDeltaException the get delta exception */ - private GetDeltaResponse calculateConfigurationDelta(String appToken, ConfigurationClientSync request, SyncContext context) + private GetDeltaResponse calculateConfigurationDelta(String appToken, + ConfigurationClientSync request, + SyncContext context) throws GetDeltaException { GetDeltaRequest deltaRequest; if (request.getConfigurationHash() != null) { - deltaRequest = new GetDeltaRequest(appToken, EndpointObjectHash.fromBytes(request.getConfigurationHash().array()), + deltaRequest = new GetDeltaRequest( + appToken, EndpointObjectHash.fromBytes(request.getConfigurationHash().array()), request.isResyncOnly()); } else { deltaRequest = new GetDeltaRequest(appToken); @@ -610,14 +684,19 @@ private GetDeltaResponse calculateConfigurationDelta(String appToken, Configurat * @param endSeqNumber the end seq number * @return the history delta */ - private HistoryDelta fetchHistory(String endpointKey, String applicationToken, EndpointProfileDto profile, int endSeqNumber) { + private HistoryDelta fetchHistory(String endpointKey, + String applicationToken, + EndpointProfileDto profile, + int endSeqNumber) { if (isFirstRequest(profile)) { LOG.debug("[{}] Profile has no endpoint groups yet. Calculating full list", endpointKey); return historyDeltaService.getDelta(profile, applicationToken, endSeqNumber); } else { - LOG.debug("[{}] Profile has endpoint groups. Calculating changes from {} to {}", endpointKey, profile.getSequenceNumber(), + LOG.debug("[{}] Profile has endpoint groups. Calculating changes from {} to {}", + endpointKey, profile.getSequenceNumber(), endSeqNumber); - return historyDeltaService.getDelta(profile, applicationToken, profile.getSequenceNumber(), endSeqNumber); + return historyDeltaService.getDelta( + profile, applicationToken, profile.getSequenceNumber(), endSeqNumber); } } @@ -629,7 +708,9 @@ private HistoryDelta fetchHistory(String endpointKey, String applicationToken, E * java.util.List, java.lang.String) */ @Override - public ServerSync updateSyncResponse(ServerSync response, List notificationDtos, String unicastNotificationId) { + public ServerSync updateSyncResponse(ServerSync response, + List notificationDtos, + String unicastNotificationId) { LOG.debug("Updating sync response {}", response); boolean modified = false; NotificationServerSync notificationResponse = response.getNotificationSync(); @@ -655,27 +736,33 @@ public ServerSync updateSyncResponse(ServerSync response, List modified = true; notifications.add(newNotification); } else { - LOG.debug("Notification with seq number {} is already present in response", newNotification.getSeqNumber()); + LOG.debug("Notification with seq number {} is already present in response", + newNotification.getSeqNumber()); } } if (unicastNotificationId != null) { boolean found = false; for (Notification oldNotification : notifications) { - if (oldNotification.getUid() != null && oldNotification.getUid().equals(unicastNotificationId)) { + if (oldNotification.getUid() != null + && oldNotification.getUid().equals(unicastNotificationId)) { found = true; break; } } if (!found) { modified = true; - NotificationDto unicast = notificationDeltaService.findUnicastNotificationById(unicastNotificationId); + NotificationDto unicast = notificationDeltaService.findUnicastNotificationById( + unicastNotificationId); if (unicast != null) { notifications.add(convertNotification(unicast)); } else { - LOG.warn("Notification with id {} was not found! Possible duplication of events from client.", unicastNotificationId); + LOG.warn("Notification with id {} was not found! " + + "Possible duplication of events from client.", + unicastNotificationId); } } else { - LOG.debug("Notification with uid [{}] is already present in response", unicastNotificationId); + LOG.debug("Notification with uid [{}] is already present in response", + unicastNotificationId); } } @@ -695,7 +782,9 @@ public void setPublicKey(PublicKey publicKey) { } @Override - public EndpointProfileDto attachEndpointToUser(EndpointProfileDto profile, String appToken, String userExternalId) { + public EndpointProfileDto attachEndpointToUser(EndpointProfileDto profile, + String appToken, + String userExternalId) { return endpointUserService.attachEndpointToUser(profile, appToken, userExternalId); } 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 61fae750fa..f01a9f25bc 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 @@ -97,20 +97,29 @@ import java.util.UUID; import java.util.concurrent.TimeUnit; -public class LocalEndpointActorMessageProcessor extends AbstractEndpointActorMessageProcessor { +public class LocalEndpointActorMessageProcessor + extends AbstractEndpointActorMessageProcessor { /** * The Constant LOG. */ - private static final Logger LOG = LoggerFactory.getLogger(LocalEndpointActorMessageProcessor.class); + private static final Logger LOG = LoggerFactory.getLogger( + LocalEndpointActorMessageProcessor.class); private final Map logUploadResponseMap; private final Map userAttachResponseMap; - public LocalEndpointActorMessageProcessor(AkkaContext context, String appToken, EndpointObjectHash key, String actorKey) { - super(new LocalEndpointActorState(Base64Util.encode(key.getData()), actorKey), context.getOperationsService(), appToken, key, - actorKey, Base64Util.encode(key.getData()), context.getLocalEndpointTimeout()); + public LocalEndpointActorMessageProcessor(AkkaContext context, + String appToken, + EndpointObjectHash key, + String actorKey) { + super(new LocalEndpointActorState(Base64Util.encode(key.getData()), actorKey), + context.getOperationsService(), appToken, + key, + actorKey, + Base64Util.encode(key.getData()), + context.getLocalEndpointTimeout()); this.logUploadResponseMap = new HashMap<>(); this.userAttachResponseMap = new LinkedHashMap<>(); } @@ -119,7 +128,8 @@ public void processEndpointSync(ActorContext context, SyncRequestMessage message sync(context, message); } - public void processEndpointEventReceiveMessage(ActorContext context, EndpointEventReceiveMessage message) { + public void processEndpointEventReceiveMessage(ActorContext context, + EndpointEventReceiveMessage message) { EndpointEventDeliveryMessage response; if (state.isValidForEvents()) { Set eventChannels = state.getChannelsByType(TransportType.EVENT); @@ -129,13 +139,15 @@ public void processEndpointEventReceiveMessage(ActorContext context, EndpointEve } response = new EndpointEventDeliveryMessage(message, EventDeliveryStatus.SUCCESS); } else { - LOG.debug("[{}] Message ignored due to no channel contexts registered for events", actorKey, message); + LOG.debug("[{}] Message ignored due to no channel contexts registered for events", + actorKey, message); response = new EndpointEventDeliveryMessage(message, EventDeliveryStatus.FAILURE); state.setUserRegistrationPending(false); } } else { LOG.debug( - "[{}][{}] Endpoint profile is not valid for receiving events. Either no assigned user or no event families in sdk", + "[{}][{}] Endpoint profile is not valid for receiving events. " + + "Either no assigned user or no event families in sdk", endpointKey, actorKey); response = new EndpointEventDeliveryMessage(message, EventDeliveryStatus.FAILURE); } @@ -143,12 +155,15 @@ public void processEndpointEventReceiveMessage(ActorContext context, EndpointEve } public void processThriftNotification(ActorContext context) { - Set channels = state.getChannelsByTypes(TransportType.CONFIGURATION, TransportType.NOTIFICATION); - LOG.debug("[{}][{}] Processing thrift norification for {} channels", endpointKey, actorKey, channels.size()); + Set channels = state.getChannelsByTypes( + TransportType.CONFIGURATION, TransportType.NOTIFICATION); + LOG.debug("[{}][{}] Processing thrift norification for {} channels", + endpointKey, actorKey, channels.size()); syncChannels(context, channels, true, true); } - public void processUserConfigurationUpdate(ActorContext context, EndpointUserConfigurationUpdateMessage message) { + public void processUserConfigurationUpdate(ActorContext context, + EndpointUserConfigurationUpdateMessage message) { if (message.getUserConfigurationUpdate() != null) { state.setUcfHash(message.getUserConfigurationUpdate().getHash()); syncChannels(context, state.getChannelsByTypes(TransportType.CONFIGURATION), true, false); @@ -163,27 +178,34 @@ protected void processThriftMsg(ActorContext context, ThriftEndpointActorMsg } else if (thriftMsg instanceof ThriftUnicastNotificationMessage) { processUnicastNotificationMsg(context, (ThriftUnicastNotificationMessage) thriftMsg); } else if (thriftMsg instanceof ThriftEndpointDeregistrationMessage) { - processEndpointDeregistrationMessage(context, (ThriftEndpointDeregistrationMessage) thriftMsg); + processEndpointDeregistrationMessage( + context, (ThriftEndpointDeregistrationMessage) thriftMsg); } } - private void processServerProfileUpdateMsg(ActorContext context, ThriftServerProfileUpdateMessage thriftMsg) { + private void processServerProfileUpdateMsg(ActorContext context, + ThriftServerProfileUpdateMessage thriftMsg) { EndpointProfileDto endpointProfile = state.getProfile(); if (endpointProfile != null) { state.setProfile(operationsService.refreshServerEndpointProfile(key)); - Set channels = state.getChannelsByTypes(TransportType.CONFIGURATION, TransportType.NOTIFICATION); - LOG.debug("[{}][{}] Processing profile update for {} channels", endpointKey, actorKey, channels.size()); + Set channels = state.getChannelsByTypes( + TransportType.CONFIGURATION, TransportType.NOTIFICATION); + LOG.debug("[{}][{}] Processing profile update for {} channels", + endpointKey, actorKey, channels.size()); syncChannels(context, channels, true, true); } else { - LOG.warn("[{}][{}] Can't update server profile for an empty state", endpointKey, actorKey); + LOG.warn("[{}][{}] Can't update server profile for an empty state", + endpointKey, actorKey); } } - private void processUnicastNotificationMsg(ActorContext context, ThriftUnicastNotificationMessage thriftMsg) { + private void processUnicastNotificationMsg(ActorContext context, + ThriftUnicastNotificationMessage thriftMsg) { processNotification(context, NotificationMessage.fromUnicastId(thriftMsg.getNotificationId())); } - private void processEndpointDeregistrationMessage(ActorContext context, ThriftEndpointDeregistrationMessage thriftMsg) { + private void processEndpointDeregistrationMessage( + ActorContext context, ThriftEndpointDeregistrationMessage thriftMsg) { for (ChannelMetaData channel : state.getAllChannels()) { sendReply(context, channel.request, new EndpointRevocationException()); } @@ -204,12 +226,15 @@ public void processNotification(ActorContext context, NotificationMessage messag return; } for (ChannelMetaData channel : channels) { - LOG.debug("[{}][{}] processing channel {} and response {}", endpointKey, actorKey, channel, + LOG.debug("[{}][{}] processing channel {} and response {}", + endpointKey, actorKey, channel, channel.getResponseHolder().getResponse()); - ServerSync syncResponse = operationsService.updateSyncResponse(channel.getResponseHolder().getResponse(), validNfs, + ServerSync syncResponse = operationsService.updateSyncResponse( + channel.getResponseHolder().getResponse(), validNfs, unicastNotificationId); if (syncResponse != null) { - LOG.debug("[{}][{}] processed channel {} and response {}", endpointKey, actorKey, channel, syncResponse); + LOG.debug("[{}][{}] processed channel {} and response {}", + endpointKey, actorKey, channel, syncResponse); sendReply(context, channel.getRequestMessage(), syncResponse); if (!channel.getType().isAsync()) { state.removeChannel(channel); @@ -227,7 +252,8 @@ public void processRequestTimeoutMessage(ActorContext context, RequestTimeoutMes state.removeChannel(channel); } } else { - LOG.debug("[{}][{}] Failed to find request by id [{}].", endpointKey, actorKey, message.getRequestId()); + LOG.debug("[{}][{}] Failed to find request by id [{}].", + endpointKey, actorKey, message.getRequestId()); } } @@ -241,7 +267,8 @@ private void sync(ActorContext context, SyncRequestMessage requestMessage) { ClientSync request = mergeRequestForChannel(channel, requestMessage); ChannelType channelType = channel.getType(); - LOG.debug("[{}][{}] Processing sync request {} from {} channel [{}]", endpointKey, actorKey, request, channelType, + LOG.debug("[{}][{}] Processing sync request {} from {} channel [{}]", + endpointKey, actorKey, request, channelType, requestMessage.getChannelUuid()); SyncContext responseHolder = sync(request); @@ -255,38 +282,43 @@ private void sync(ActorContext context, SyncRequestMessage requestMessage) { processEvents(context, request, responseHolder); notifyAffectedEndpoints(context, request, responseHolder); } else { - LOG.warn("[{}][{}] Endpoint profile is not set after request processing!", endpointKey, actorKey); + LOG.warn("[{}][{}] Endpoint profile is not set after request processing!", + endpointKey, actorKey); } LOG.debug("[{}][{}] SyncResponseHolder {}", endpointKey, actorKey, responseHolder); if (channelType.isAsync()) { - LOG.debug("[{}][{}] Adding async request from channel [{}] to map ", endpointKey, actorKey, + LOG.debug("[{}][{}] Adding async request from channel [{}] to map ", + endpointKey, actorKey, requestMessage.getChannelUuid()); channel.update(responseHolder); updateSubscriptionsToTopics(context, responseHolder); sendReply(context, requestMessage, responseHolder.getResponse()); } else { if (channelType.isLongPoll() && !responseHolder.requireImmediateReply()) { - LOG.debug("[{}][{}] Adding long poll request from channel [{}] to map ", endpointKey, actorKey, + LOG.debug("[{}][{}] Adding long poll request from channel [{}] to map ", + endpointKey, actorKey, requestMessage.getChannelUuid()); channel.update(responseHolder); updateSubscriptionsToTopics(context, responseHolder); - scheduleTimeoutMessage(context, requestMessage.getChannelUuid(), getDelay(requestMessage, start)); + scheduleTimeoutMessage( + context, requestMessage.getChannelUuid(), getDelay(requestMessage, start)); } else { sendReply(context, requestMessage, responseHolder.getResponse()); state.removeChannel(channel); } } - } catch (Exception e) { - LOG.error("[{}][{}] processEndpointRequest", endpointKey, actorKey, e); - sendReply(context, requestMessage, e); + } catch (Exception ex) { + LOG.error("[{}][{}] processEndpointRequest", endpointKey, actorKey, ex); + sendReply(context, requestMessage, ex); } } private SyncContext sync(ClientSync request) throws GetDeltaException { if (!request.isValid()) { - LOG.warn("[{}] Request is not valid. It does not contain profile information!", endpointKey); + LOG.warn("[{}] Request is not valid. It does not contain profile information!", + endpointKey); return SyncContext.failure(request.getRequestId()); } SyncContext context = new SyncContext(new ServerSync()); @@ -297,23 +329,26 @@ private SyncContext sync(ClientSync request) throws GetDeltaException { context.setRequestHash(request.hashCode()); context.setMetaData(request.getClientSyncMetaData()); - - LOG.trace("[{}][{}] processing sync. Request: {}", endpointKey, context.getRequestHash(), request); + LOG.trace("[{}][{}] processing sync. Request: {}", + endpointKey, context.getRequestHash(), request); context = operationsService.syncClientProfile(context, request.getProfileSync()); - context = operationsService.syncUseConfigurationRawSchema(context, request.isUseConfigurationRawSchema()); + context = operationsService.syncUseConfigurationRawSchema( + context, request.isUseConfigurationRawSchema()); if (context.getStatus() != SyncStatus.SUCCESS) { return context; } if (state.isUcfHashRequiresIntialization()) { byte[] hash = operationsService.fetchUcfHash(appToken, state.getProfile()); - LOG.debug("[{}][{}] Initialized endpoint user configuration hash {}", endpointKey, context.getRequestHash(), + LOG.debug("[{}][{}] Initialized endpoint user configuration hash {}", + endpointKey, context.getRequestHash(), Arrays.toString(hash)); state.setUcfHash(hash); } - context = operationsService.processEndpointAttachDetachRequests(context, request.getUserSync()); + context = operationsService.processEndpointAttachDetachRequests( + context, request.getUserSync()); context = operationsService.processEventListenerRequests(context, request.getEventSync()); if (state.isUserConfigurationUpdatePending()) { @@ -324,12 +359,15 @@ private SyncContext sync(ClientSync request) throws GetDeltaException { context = operationsService.syncNotification(context, request.getNotificationSync()); - LOG.trace("[{}][{}] processed sync. Response is {}", endpointKey, request.hashCode(), context.getResponse()); + LOG.trace("[{}][{}] processed sync. Response is {}", + endpointKey, request.hashCode(), context.getResponse()); return context; } - private void syncChannels(ActorContext context, Set channels, boolean cfUpdate, boolean nfUpdate) { + private void syncChannels(ActorContext context, + Set channels, + boolean cfUpdate, boolean nfUpdate) { for (ChannelMetaData channel : channels) { ClientSync originalRequest = channel.getRequestMessage().getRequest(); ClientSync newRequest = new ClientSync(); @@ -350,15 +388,18 @@ private void syncChannels(ActorContext context, Set channels, b } } - private ClientSync mergeRequestForChannel(ChannelMetaData channel, SyncRequestMessage requestMessage) { + private ClientSync mergeRequestForChannel(ChannelMetaData channel, + SyncRequestMessage requestMessage) { ClientSync request; if (channel.getType().isAsync()) { if (channel.isFirstRequest()) { request = channel.getRequestMessage().getRequest(); } else { - LOG.debug("[{}][{}] Updating request for async channel {}", endpointKey, actorKey, channel); + LOG.debug("[{}][{}] Updating request for async channel {}", + endpointKey, actorKey, channel); request = channel.mergeRequest(requestMessage); - LOG.trace("[{}][{}] Updated request for async channel {} : {}", endpointKey, actorKey, channel, request); + LOG.trace("[{}][{}] Updated request for async channel {} : {}", + endpointKey, actorKey, channel, request); } } else { request = channel.getRequestMessage().getRequest(); @@ -366,30 +407,39 @@ private ClientSync mergeRequestForChannel(ChannelMetaData channel, SyncRequestMe return request; } - private void processUserAttachRequest(ActorContext context, ClientSync syncRequest, SyncContext responseHolder) { + private void processUserAttachRequest(ActorContext context, + ClientSync syncRequest, + SyncContext responseHolder) { UserClientSync request = syncRequest.getUserSync(); if (request != null && request.getUserAttachRequest() != null) { - UserAttachRequest aRequest = request.getUserAttachRequest(); - context.parent().tell(new UserVerificationRequestMessage(context.self(), aRequest.getUserVerifierId(), - aRequest.getUserExternalId(), aRequest.getUserAccessToken()), context.self()); - LOG.debug("[{}][{}] received and forwarded user attach request {}", endpointKey, actorKey, request.getUserAttachRequest()); + UserAttachRequest attachRequest = request.getUserAttachRequest(); + context.parent().tell(new UserVerificationRequestMessage( + context.self(), attachRequest.getUserVerifierId(), + attachRequest.getUserExternalId(), attachRequest.getUserAccessToken()), context.self()); + LOG.debug("[{}][{}] received and forwarded user attach request {}", + endpointKey, actorKey, request.getUserAttachRequest()); if (userAttachResponseMap.size() > 0) { - Entry entryToSend = userAttachResponseMap.entrySet().iterator().next(); + Entry entryToSend = userAttachResponseMap.entrySet() + .iterator() + .next(); updateResponseWithUserAttachResults(responseHolder.getResponse(), entryToSend.getValue()); userAttachResponseMap.remove(entryToSend.getKey()); } } } - private void updateResponseWithUserAttachResults(ServerSync response, UserVerificationResponseMessage message) { + private void updateResponseWithUserAttachResults(ServerSync response, + UserVerificationResponseMessage message) { if (response.getUserSync() == null) { response.setUserSync(new UserServerSync()); } response.getUserSync().setUserAttachResponse(EntityConvertUtils.convert(message)); } - private void processEvents(ActorContext context, ClientSync request, SyncContext responseHolder) { + private void processEvents(ActorContext context, + ClientSync request, + SyncContext responseHolder) { if (request.getEventSync() != null) { EventClientSync eventRequest = request.getEventSync(); processSeqNumber(eventRequest, responseHolder); @@ -397,7 +447,8 @@ private void processEvents(ActorContext context, ClientSync request, SyncContext sendEventsIfPresent(context, eventRequest); } else { LOG.debug( - "[{}][{}] Endpoint profile is not valid for send/receive events. Either no assigned user or no event families in sdk", + "[{}][{}] Endpoint profile is not valid for send/receive events. " + + "Either no assigned user or no event families in sdk", endpointKey, actorKey); } } @@ -410,7 +461,8 @@ private void processSeqNumber(EventClientSync request, SyncContext responseHolde response = new EventServerSync(); responseHolder.getResponse().setEventSync(response); } - response.setEventSequenceNumberResponse(new EventSequenceNumberResponse(Math.max(state.getEventSeqNumber(), 0))); + response.setEventSequenceNumberResponse(new EventSequenceNumberResponse( + Math.max(state.getEventSeqNumber(), 0))); } } @@ -433,11 +485,14 @@ private void updateUserConnection(ActorContext context) { } } - private void processLogUpload(ActorContext context, ClientSync syncRequest, SyncContext responseHolder) { + private void processLogUpload(ActorContext context, + ClientSync syncRequest, + SyncContext responseHolder) { LogClientSync request = syncRequest.getLogSync(); if (request != null) { if (request.getLogEntries() != null && request.getLogEntries().size() > 0) { - LOG.debug("[{}][{}] Processing log upload request {}", endpointKey, actorKey, request.getLogEntries().size()); + LOG.debug("[{}][{}] Processing log upload request {}", + endpointKey, actorKey, request.getLogEntries().size()); EndpointProfileDataDto profileDto = convert(responseHolder.getEndpointProfile()); List logEvents = new ArrayList<>(request.getLogEntries().size()); for (LogEntry logEntry : request.getLogEntries()) { @@ -448,7 +503,8 @@ private void processLogUpload(ActorContext context, ClientSync syncRequest, Sync BaseLogEventPack logPack = new BaseLogEventPack(profileDto, System.currentTimeMillis(), responseHolder.getEndpointProfile().getLogSchemaVersion(), logEvents); logPack.setUserId(state.getUserId()); - context.parent().tell(new LogEventPackMessage(request.getRequestId(), context.self(), logPack), context.self()); + context.parent().tell(new LogEventPackMessage( + request.getRequestId(), context.self(), logPack), context.self()); } if (logUploadResponseMap.size() > 0) { responseHolder.getResponse().setLogSync(EntityConvertUtils.convert(logUploadResponseMap)); @@ -458,28 +514,39 @@ private void processLogUpload(ActorContext context, ClientSync syncRequest, Sync } private EndpointProfileDataDto convert(EndpointProfileDto profileDto) { - return new EndpointProfileDataDto(profileDto.getId(), endpointKey, profileDto.getClientProfileVersion(), - profileDto.getClientProfileBody(), profileDto.getServerProfileVersion(), profileDto.getServerProfileBody()); + return new EndpointProfileDataDto( + profileDto.getId(), endpointKey, profileDto.getClientProfileVersion(), + profileDto.getClientProfileBody(), profileDto.getServerProfileVersion(), + profileDto.getServerProfileBody()); } private void sendConnectToNewUser(ActorContext context, EndpointProfileDto endpointProfile) { - List ecfVersions = EntityConvertUtils.convertToECFVersions(endpointProfile.getEcfVersionStates()); - EndpointUserConnectMessage userRegistrationMessage = new EndpointUserConnectMessage(state.getUserId(), key, ecfVersions, - endpointProfile.getConfigurationVersion(), endpointProfile.getUserConfigurationHash(), appToken, context.self()); - LOG.debug("[{}][{}] Sending user registration request {}", endpointKey, actorKey, userRegistrationMessage); + List ecfVersions = EntityConvertUtils.convertToECFVersions( + endpointProfile.getEcfVersionStates()); + EndpointUserConnectMessage userRegistrationMessage = new EndpointUserConnectMessage( + state.getUserId(), key, ecfVersions, + endpointProfile.getConfigurationVersion(), endpointProfile.getUserConfigurationHash(), + appToken, context.self()); + LOG.debug("[{}][{}] Sending user registration request {}", + endpointKey, actorKey, userRegistrationMessage); context.parent().tell(userRegistrationMessage, context.self()); } - private void sendDisconnectFromOldUser(ActorContext context, EndpointProfileDto endpointProfile) { - LOG.debug("[{}][{}] Detected user change from [{}] to [{}]", endpointKey, actorKey, state.getUserId(), + private void sendDisconnectFromOldUser(ActorContext context, + EndpointProfileDto endpointProfile) { + LOG.debug("[{}][{}] Detected user change from [{}] to [{}]", + endpointKey, actorKey, state.getUserId(), endpointProfile.getEndpointUserId()); - EndpointUserDisconnectMessage userDisconnectMessage = new EndpointUserDisconnectMessage(state.getUserId(), key, appToken, + EndpointUserDisconnectMessage userDisconnectMessage = new EndpointUserDisconnectMessage( + state.getUserId(), key, appToken, context.self()); context.parent().tell(userDisconnectMessage, context.self()); } private long getDelay(SyncRequestMessage requestMessage, long start) { - return requestMessage.getRequest().getClientSyncMetaData().getTimeout() - (System.currentTimeMillis() - start); + return requestMessage.getRequest() + .getClientSyncMetaData() + .getTimeout() - (System.currentTimeMillis() - start); } private ChannelMetaData initChannel(ActorContext context, SyncRequestMessage requestMessage) { @@ -494,8 +561,12 @@ private ChannelMetaData initChannel(ActorContext context, SyncRequestMessage req Set channels = state.getChannelsByType(TransportType.EVENT); for (ChannelMetaData oldChannel : channels) { if (!oldChannel.getType().isAsync() && channel.getType().isLongPoll()) { - LOG.debug("[{}][{}] Closing old long poll channel [{}]", endpointKey, actorKey, oldChannel.getId()); - sendReply(context, oldChannel.getRequestMessage(), oldChannel.getResponseHolder().getResponse()); + LOG.debug("[{}][{}] Closing old long poll channel [{}]", + endpointKey, actorKey, oldChannel.getId()); + sendReply( + context, + oldChannel.getRequestMessage(), + oldChannel.getResponseHolder().getResponse()); state.removeChannel(oldChannel); } } @@ -515,25 +586,34 @@ private ChannelMetaData initChannel(ActorContext context, SyncRequestMessage req } private void scheduleKeepAliveCheck(ActorContext context, ChannelMetaData channel) { - TimeoutMessage message = new ChannelTimeoutMessage(channel.getId(), channel.getLastActivityTime()); - LOG.debug("Scheduling channel timeout message: {} to timeout in {}", message, channel.getKeepAlive() * 1000); + TimeoutMessage message = new ChannelTimeoutMessage( + channel.getId(), channel.getLastActivityTime()); + LOG.debug("Scheduling channel timeout message: {} to timeout in {}", + message, channel.getKeepAlive() * 1000); scheduleTimeoutMessage(context, message, channel.getKeepAlive() * 1000); } - private void notifyAffectedEndpoints(ActorContext context, ClientSync request, SyncContext responseHolder) { + private void notifyAffectedEndpoints(ActorContext context, ClientSync request, + SyncContext responseHolder) { if (responseHolder.getResponse().getUserSync() != null) { - List attachResponses = responseHolder.getResponse().getUserSync().getEndpointAttachResponses(); + List attachResponses = responseHolder.getResponse() + .getUserSync() + .getEndpointAttachResponses(); if (attachResponses != null && !attachResponses.isEmpty()) { state.resetEventSeqNumber(); for (EndpointAttachResponse response : attachResponses) { if (response.getResult() != SyncStatus.SUCCESS) { - LOG.debug("[{}][{}] Skipped unsuccessful attach response [{}]", endpointKey, actorKey, response.getRequestId()); + LOG.debug("[{}][{}] Skipped unsuccessful attach response [{}]", + endpointKey, actorKey, response.getRequestId()); continue; } EndpointUserAttachMessage attachMessage = new EndpointUserAttachMessage( - EndpointObjectHash.fromBytes(Base64Util.decode(response.getEndpointKeyHash())), state.getUserId(), endpointKey); + EndpointObjectHash.fromBytes( + Base64Util.decode(response.getEndpointKeyHash())), + state.getUserId(), endpointKey); context.parent().tell(attachMessage, context.self()); - LOG.debug("[{}][{}] Notification to attached endpoint [{}] sent", endpointKey, actorKey, response.getEndpointKeyHash()); + LOG.debug("[{}][{}] Notification to attached endpoint [{}] sent", + endpointKey, actorKey, response.getEndpointKeyHash()); } } @@ -542,18 +622,24 @@ private void notifyAffectedEndpoints(ActorContext context, ClientSync request, S if (detachRequests != null && !detachRequests.isEmpty()) { state.resetEventSeqNumber(); for (EndpointDetachRequest detachRequest : detachRequests) { - for (EndpointDetachResponse detachResponse : responseHolder.getResponse().getUserSync().getEndpointDetachResponses()) { + List endpointDetachResponses = responseHolder.getResponse() + .getUserSync() + .getEndpointDetachResponses(); + for (EndpointDetachResponse detachResponse : endpointDetachResponses) { if (detachRequest.getRequestId() == detachResponse.getRequestId()) { if (detachResponse.getResult() != SyncStatus.SUCCESS) { - LOG.debug("[{}][{}] Skipped unsuccessful detach response [{}]", endpointKey, actorKey, + LOG.debug("[{}][{}] Skipped unsuccessful detach response [{}]", + endpointKey, actorKey, detachResponse.getRequestId()); continue; } EndpointUserDetachMessage attachMessage = new EndpointUserDetachMessage( - EndpointObjectHash.fromBytes(Base64Util.decode(detachRequest.getEndpointKeyHash())), state.getUserId(), + EndpointObjectHash.fromBytes( + Base64Util.decode(detachRequest.getEndpointKeyHash())), state.getUserId(), endpointKey); context.parent().tell(attachMessage, context.self()); - LOG.debug("[{}][{}] Notification to detached endpoint [{}] sent", endpointKey, actorKey, + LOG.debug("[{}][{}] Notification to detached endpoint [{}] sent", + endpointKey, actorKey, detachRequest.getEndpointKeyHash()); } } @@ -564,7 +650,8 @@ private void notifyAffectedEndpoints(ActorContext context, ClientSync request, S protected void scheduleActorTimeout(ActorContext context) { if (state.isNoChannels()) { - scheduleTimeoutMessage(context, new ActorTimeoutMessage(state.getLastActivityTime()), getInactivityTimeout()); + scheduleTimeoutMessage( + context, new ActorTimeoutMessage(state.getLastActivityTime()), getInactivityTimeout()); } } @@ -585,7 +672,10 @@ private void updateSubscriptionsToTopics(ActorContext context, SyncContext respo String subscribedTopic = currentSubscriptionsIterator.next(); if (!newStates.containsKey(subscribedTopic)) { currentSubscriptionsIterator.remove(); - TopicUnsubscriptionMessage topicSubscriptionMessage = new TopicUnsubscriptionMessage(subscribedTopic, appToken, key, + TopicUnsubscriptionMessage topicSubscriptionMessage = new TopicUnsubscriptionMessage( + subscribedTopic, + appToken, + key, context.self()); context.parent().tell(topicSubscriptionMessage, context.self()); } @@ -593,8 +683,13 @@ private void updateSubscriptionsToTopics(ActorContext context, SyncContext respo // subscribe to new topics; for (Entry entry : newStates.entrySet()) { if (!currentStates.containsKey(entry.getKey())) { - TopicSubscriptionMessage topicSubscriptionMessage = new TopicSubscriptionMessage(entry.getKey(), entry.getValue(), - response.getSystemNfVersion(), response.getUserNfVersion(), appToken, key, context.self()); + TopicSubscriptionMessage topicSubscriptionMessage = new TopicSubscriptionMessage( + entry.getKey(), entry.getValue(), + response.getSystemNfVersion(), + response.getUserNfVersion(), + appToken, + key, + context.self()); context.parent().tell(topicSubscriptionMessage, context.self()); } } @@ -606,11 +701,16 @@ private void scheduleTimeoutMessage(ActorContext context, UUID requestId, long d } private void scheduleTimeoutMessage(ActorContext context, TimeoutMessage message, long delay) { - context.system().scheduler().scheduleOnce(Duration.create(delay, TimeUnit.MILLISECONDS), context.self(), message, - context.dispatcher(), context.self()); + context.system() + .scheduler() + .scheduleOnce( + Duration.create(delay, TimeUnit.MILLISECONDS), context.self(), message, + context.dispatcher(), context.self()); } - private void addEventsAndReply(ActorContext context, ChannelMetaData channel, EndpointEventReceiveMessage message) { + private void addEventsAndReply(ActorContext context, + ChannelMetaData channel, + EndpointEventReceiveMessage message) { SyncRequestMessage pendingRequest = channel.getRequestMessage(); SyncContext pendingResponse = channel.getResponseHolder(); @@ -627,21 +727,25 @@ private void addEventsAndReply(ActorContext context, ChannelMetaData channel, En } } - private void sendReply(ActorContext context, SyncRequestMessage request, ServerSync syncResponse) { + private void sendReply(ActorContext context, + SyncRequestMessage request, + ServerSync syncResponse) { sendReply(context, request, null, syncResponse); } - private void sendReply(ActorContext context, SyncRequestMessage request, Exception e) { - sendReply(context, request, e, null); + private void sendReply(ActorContext context, SyncRequestMessage request, Exception ex) { + sendReply(context, request, ex, null); } - private void sendReply(ActorContext context, SyncRequestMessage request, Exception e, ServerSync syncResponse) { + private void sendReply(ActorContext context, SyncRequestMessage request, + Exception ex, ServerSync syncResponse) { LOG.debug("[{}] response: {}", actorKey, syncResponse); ServerSync copy = ServerSync.deepCopy(syncResponse); ServerSync.cleanup(syncResponse); - NettySessionResponseMessage response = new NettySessionResponseMessage(request.getSession(), copy, e, + NettySessionResponseMessage response = new NettySessionResponseMessage( + request.getSession(), copy, ex, request.getCommand().getMessageBuilder(), request.getCommand().getErrorBuilder()); tellActor(context, request.getOriginator(), response); @@ -651,7 +755,8 @@ private void sendReply(ActorContext context, SyncRequestMessage request, Excepti protected void sendEventsIfPresent(ActorContext context, EventClientSync request) { List events = request.getEvents(); if (state.getUserId() != null && events != null && !events.isEmpty()) { - LOG.debug("[{}][{}] Processing events {} with seq number > {}", endpointKey, actorKey, events, state.getEventSeqNumber()); + LOG.debug("[{}][{}] Processing events {} with seq number > {}", + endpointKey, actorKey, events, state.getEventSeqNumber()); List eventsToSend = new ArrayList<>(events.size()); int maxSentEventSeqNum = state.getEventSeqNumber(); for (Event event : events) { @@ -660,29 +765,38 @@ protected void sendEventsIfPresent(ActorContext context, EventClientSync request eventsToSend.add(event); maxSentEventSeqNum = Math.max(event.getSeqNum(), maxSentEventSeqNum); } else { - LOG.debug("[{}][{}] Ignoring duplicate/old event {} due to seq number < {}", endpointKey, actorKey, events, + LOG.debug("[{}][{}] Ignoring duplicate/old event {} due to seq number < {}", + endpointKey, actorKey, events, state.getEventSeqNumber()); } } state.setEventSeqNumber(maxSentEventSeqNum); if (!eventsToSend.isEmpty()) { - EndpointEventSendMessage message = new EndpointEventSendMessage(state.getUserId(), eventsToSend, key, appToken, + EndpointEventSendMessage message = new EndpointEventSendMessage( + state.getUserId(), eventsToSend, key, appToken, context.self()); context.parent().tell(message, context.self()); } } } - public void processEndpointUserActionMessage(ActorContext context, EndpointUserActionMessage message) { - Set eventChannels = state.getChannelsByTypes(TransportType.EVENT, TransportType.USER); - LOG.debug("[{}][{}] Current Endpoint was attached/detached from user. Need to close all current event channels {}", endpointKey, - actorKey, eventChannels.size()); + public void processEndpointUserActionMessage(ActorContext context, + EndpointUserActionMessage message) { + Set eventChannels = state.getChannelsByTypes( + TransportType.EVENT, TransportType.USER); + LOG.debug("[{}][{}] Current Endpoint was attached/detached from user. " + + "Need to close all current event channels {}", + endpointKey, + actorKey, + eventChannels.size()); state.setUserRegistrationPending(false); state.setProfile(operationsService.refreshServerEndpointProfile(key)); if (message instanceof EndpointUserAttachMessage) { - LOG.debug("[{}][{}] Updating endpoint user id to {} in profile", endpointKey, actorKey, message.getUserId()); + LOG.debug("[{}][{}] Updating endpoint user id to {} in profile", + endpointKey, actorKey, message.getUserId()); } else if (message instanceof EndpointUserDetachMessage) { - LOG.debug("[{}][{}] Clanup endpoint user id in profile", endpointKey, actorKey, message.getUserId()); + LOG.debug("[{}][{}] Clanup endpoint user id in profile", + endpointKey, actorKey, message.getUserId()); } if (!eventChannels.isEmpty()) { @@ -700,79 +814,96 @@ public void processEndpointUserActionMessage(ActorContext context, EndpointUserA if (userSyncResponse != null) { if (message instanceof EndpointUserAttachMessage) { userSyncResponse - .setUserAttachNotification(new UserAttachNotification(message.getUserId(), message.getOriginator())); + .setUserAttachNotification( + new UserAttachNotification(message.getUserId(), message.getOriginator())); LOG.debug("[{}][{}] Adding user attach notification", endpointKey, actorKey); } else if (message instanceof EndpointUserDetachMessage) { - userSyncResponse.setUserDetachNotification(new UserDetachNotification(message.getOriginator())); + userSyncResponse.setUserDetachNotification( + new UserDetachNotification(message.getOriginator())); LOG.debug("[{}][{}] Adding user detach notification", endpointKey, actorKey); } } - LOG.debug("[{}][{}] sending reply to [{}] channel", endpointKey, actorKey, channel.getId()); + LOG.debug("[{}][{}] sending reply to [{}] channel", + endpointKey, actorKey, channel.getId()); sendReply(context, pendingRequest, pendingResponse); if (!channel.getType().isAsync()) { state.removeChannel(channel); } } } else { - LOG.debug("[{}][{}] Message ignored due to no channel contexts registered for events", endpointKey, actorKey, message); + LOG.debug("[{}][{}] Message ignored due to no channel contexts registered for events", + endpointKey, actorKey, message); } } public boolean processDisconnectMessage(ActorContext context, ChannelAware message) { - LOG.debug("[{}][{}] Received disconnect message for channel [{}]", endpointKey, actorKey, message.getChannelUuid()); + LOG.debug("[{}][{}] Received disconnect message for channel [{}]", + endpointKey, actorKey, message.getChannelUuid()); ChannelMetaData channel = state.getChannelById(message.getChannelUuid()); if (channel != null) { state.removeChannel(channel); scheduleActorTimeout(context); return true; } else { - LOG.debug("[{}][{}] Can't find channel by uuid [{}]", endpointKey, actorKey, message.getChannelUuid()); + LOG.debug("[{}][{}] Can't find channel by uuid [{}]", + endpointKey, actorKey, message.getChannelUuid()); return false; } } public boolean processPingMessage(ActorContext context, ChannelAware message) { - LOG.debug("[{}][{}] Received ping message for channel [{}]", endpointKey, actorKey, message.getChannelUuid()); + LOG.debug("[{}][{}] Received ping message for channel [{}]", + endpointKey, actorKey, message.getChannelUuid()); ChannelMetaData channel = state.getChannelById(message.getChannelUuid()); if (channel != null) { long lastActivityTime = System.currentTimeMillis(); - LOG.debug("[{}][{}] Updating last activity time for channel [{}] to ", endpointKey, actorKey, message.getChannelUuid(), + LOG.debug("[{}][{}] Updating last activity time for channel [{}] to ", + endpointKey, actorKey, message.getChannelUuid(), lastActivityTime); channel.setLastActivityTime(lastActivityTime); channel.getContext().writeAndFlush(new PingResponse()); return true; } else { - LOG.debug("[{}][{}] Can't find channel by uuid [{}]", endpointKey, actorKey, message.getChannelUuid()); + LOG.debug("[{}][{}] Can't find channel by uuid [{}]", + endpointKey, actorKey, message.getChannelUuid()); return false; } } - public boolean processChannelTimeoutMessage(ActorContext context, ChannelTimeoutMessage message) { - LOG.debug("[{}][{}] Received channel timeout message for channel [{}]", endpointKey, actorKey, message.getChannelUuid()); + public boolean processChannelTimeoutMessage(ActorContext context, + ChannelTimeoutMessage message) { + LOG.debug("[{}][{}] Received channel timeout message for channel [{}]", + endpointKey, actorKey, message.getChannelUuid()); ChannelMetaData channel = state.getChannelById(message.getChannelUuid()); if (channel != null) { if (channel.getLastActivityTime() <= message.getLastActivityTime()) { - LOG.debug("[{}][{}] Timeout message accepted for channel [{}]. Last activity time {} and timeout is {} ", endpointKey, - actorKey, message.getChannelUuid(), channel.getLastActivityTime(), message.getLastActivityTime()); + LOG.debug("[{}][{}] Timeout message accepted for channel [{}]. " + + "Last activity time {} and timeout is {} ", + endpointKey, actorKey, message.getChannelUuid(), + channel.getLastActivityTime(), message.getLastActivityTime()); state.removeChannel(channel); scheduleActorTimeout(context); return true; } else { - LOG.debug("[{}][{}] Timeout message ignored for channel [{}]. Last activity time {} and timeout is {} ", endpointKey, - actorKey, message.getChannelUuid(), channel.getLastActivityTime(), message.getLastActivityTime()); + LOG.debug("[{}][{}] Timeout message ignored for channel [{}]. " + + "Last activity time {} and timeout is {} ", + endpointKey, actorKey, message.getChannelUuid(), + channel.getLastActivityTime(), message.getLastActivityTime()); scheduleKeepAliveCheck(context, channel); return false; } } else { - LOG.debug("[{}][{}] Can't find channel by uuid [{}]", endpointKey, actorKey, message.getChannelUuid()); + LOG.debug("[{}][{}] Can't find channel by uuid [{}]", + endpointKey, actorKey, message.getChannelUuid()); scheduleActorTimeout(context); return false; } } public void processLogDeliveryMessage(ActorContext context, LogDeliveryMessage message) { - LOG.debug("[{}][{}] Received log delivery message for request [{}] with status {}", endpointKey, actorKey, message.getRequestId(), + LOG.debug("[{}][{}] Received log delivery message for request [{}] with status {}", + endpointKey, actorKey, message.getRequestId(), message.isSuccess()); logUploadResponseMap.put(message.getRequestId(), message); Set channels = state.getChannelsByType(TransportType.LOGGING); @@ -791,12 +922,16 @@ public void processLogDeliveryMessage(ActorContext context, LogDeliveryMessage m logUploadResponseMap.clear(); } - public void processUserVerificationMessage(ActorContext context, UserVerificationResponseMessage message) { - LOG.debug("[{}][{}] Received user verification message for request [{}] with status {}", endpointKey, actorKey, + public void processUserVerificationMessage(ActorContext context, + UserVerificationResponseMessage message) { + LOG.debug("[{}][{}] Received user verification message for request [{}] with status {}", + endpointKey, actorKey, message.getRequestId(), message.isSuccess()); userAttachResponseMap.put(message.getRequestId(), message); Set channels = state.getChannelsByType(TransportType.USER); - Entry entryToSend = userAttachResponseMap.entrySet().iterator().next(); + Entry entryToSend = userAttachResponseMap.entrySet() + .iterator() + .next(); for (ChannelMetaData channel : channels) { SyncRequestMessage pendingRequest = channel.getRequestMessage(); ServerSync pendingResponse = channel.getResponseHolder().getResponse(); @@ -811,7 +946,9 @@ public void processUserVerificationMessage(ActorContext context, UserVerificatio } userAttachResponseMap.remove(entryToSend.getKey()); if (message.isSuccess()) { - state.setProfile(operationsService.attachEndpointToUser(state.getProfile(), appToken, message.getUserId())); + state.setProfile( + operationsService.attachEndpointToUser( + state.getProfile(), appToken, message.getUserId())); updateUserConnection(context); } } 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 591ace583a..bda72aceb2 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 @@ -135,7 +135,8 @@ void processClusterUpdate(ActorContext context) { } } - void processEndpointDisconnectMessage(ActorContext context, EndpointUserDisconnectMessage message) { + void processEndpointDisconnectMessage(ActorContext context, + EndpointUserDisconnectMessage message) { List actorsToRemove = new LinkedList<>(); for (Entry entry : endpoints.entrySet()) { if (entry.getValue().equals(message.getKey())) { @@ -157,33 +158,41 @@ void processEndpointEventSendMessage(ActorContext context, EndpointEventSendMess } } - void processRemoteEndpointEventMessage(ActorContext context, RemoteEndpointEventMessage message) { + void processRemoteEndpointEventMessage(ActorContext context, + RemoteEndpointEventMessage message) { LOG.debug("[{}] Processing remote event message: {}", userId, message); EndpointEvent localEvent = message.getEvent().toLocalEvent(); processEvent(context, localEvent); } - void processEndpointEventTimeoutMessage(ActorContext context, EndpointEventTimeoutMessage message) { - LOG.debug("[{}] processing event timeout message for [{}]", userId, message.getEvent().getId()); + void processEndpointEventTimeoutMessage(ActorContext context, + EndpointEventTimeoutMessage message) { + LOG.debug("[{}] processing event timeout message for [{}]", + userId, message.getEvent().getId()); if (eventStorage.clear(message.getEvent())) { LOG.debug("[{}] removed event [{}] from storage", userId, message.getEvent().getId()); } if (eventDeliveryTable.clear(message.getEvent())) { - LOG.debug("[{}] removed event [{}] from delivery table", userId, message.getEvent().getId()); + LOG.debug("[{}] removed event [{}] from delivery table", + userId, message.getEvent().getId()); } } - void processEndpointEventDeliveryMessage(ActorContext context, EndpointEventDeliveryMessage message) { - LOG.debug("[{}] processing event delivery message for [{}] with status {}", userId, message.getMessage().getAddress(), + void processEndpointEventDeliveryMessage(ActorContext context, + EndpointEventDeliveryMessage message) { + LOG.debug("[{}] processing event delivery message for [{}] with status {}", + userId, message.getMessage().getAddress(), message.getStatus()); boolean success = message.getStatus() == EventDeliveryStatus.SUCCESS; RouteTableAddress address = message.getMessage().getAddress(); for (EndpointEvent event : message.getMessage().getEndpointEvents()) { if (success) { - LOG.debug("[{}] registering successful delivery of event [{}] to address {}", userId, event.getId(), address); + LOG.debug("[{}] registering successful delivery of event [{}] to address {}", + userId, event.getId(), address); eventDeliveryTable.registerDeliverySuccess(event, address); } else { - LOG.debug("[{}] registering failure to delivery of event [{}] to address {}", userId, event.getId(), address); + LOG.debug("[{}] registering failure to delivery of event [{}] to address {}", + userId, event.getId(), address); eventDeliveryTable.registerDeliveryFailure(event, address); } } @@ -192,12 +201,15 @@ void processEndpointEventDeliveryMessage(ActorContext context, EndpointEventDeli void processRouteInfoMessage(ActorContext context, RouteInfoMessage message) { RouteInfo routeInfo = message.getRouteInfo(); if (RouteOperation.DELETE.equals(routeInfo.getRouteOperation())) { - LOG.debug("[{}] Removing all routes from route table by address {}", userId, routeInfo.getAddress()); + LOG.debug("[{}] Removing all routes from route table by address {}", + userId, routeInfo.getAddress()); routeTable.removeByAddress(routeInfo.getAddress()); } else { for (EventClassFamilyVersion ecfVersion : routeInfo.getEcfVersions()) { - RouteTableKey key = new RouteTableKey(routeInfo.getAddress().getApplicationToken(), ecfVersion); - LOG.debug("[{}] Updating route table with key {} and address {}", userId, key, routeInfo.getAddress()); + RouteTableKey key = new RouteTableKey( + routeInfo.getAddress().getApplicationToken(), ecfVersion); + LOG.debug("[{}] Updating route table with key {} and address {}", + userId, key, routeInfo.getAddress()); updateRouteTable(context, key, routeInfo.getAddress()); } } @@ -206,7 +218,8 @@ void processRouteInfoMessage(ActorContext context, RouteInfoMessage message) { void processUserRouteInfoMessage(ActorContext context, UserRouteInfoMessage message) { UserRouteInfo userRouteInfo = message.getRouteInfo(); - LOG.debug("[{}] Cleanup all route table data related to serverId: {}", userId, userRouteInfo.getServerId()); + LOG.debug("[{}] Cleanup all route table data related to serverId: {}", + userId, userRouteInfo.getServerId()); routeTable.clearRemoteServerData(userRouteInfo.getServerId()); if (!RouteOperation.DELETE.equals(userRouteInfo.getRouteOperation())) { reportAllLocalRoutes(userRouteInfo.getServerId()); @@ -229,7 +242,8 @@ void processTerminationMessage(ActorContext context, Terminated message) { } if (stilPresent) { LOG.debug("[{}] received termination message for endpoint actor [{}], " - + "but other actor is still registered for this endpoint.", userId, localActor); + + "but other actor is still registered for this endpoint.", + userId, localActor); } else { removeEndpoint(context, endpoint); LOG.debug("[{}] removed endpoint [{}]", userId, localActor); @@ -240,7 +254,9 @@ void processTerminationMessage(ActorContext context, Terminated message) { } } - private void registerEndpointForEvents(ActorContext context, EndpointUserConnectMessage message, RouteTableAddress address) { + private void registerEndpointForEvents(ActorContext context, + EndpointUserConnectMessage message, + RouteTableAddress address) { List ecfVersions = message.getEcfVersions(); if (!ecfVersions.isEmpty()) { for (EventClassFamilyVersion ecfVersion : ecfVersions) { @@ -254,8 +270,10 @@ private void registerEndpointForEvents(ActorContext context, EndpointUserConnect } for (String serverId : routeTable.getRemoteServers()) { if (routeTable.isDeliveryRequired(serverId, address)) { - LOG.debug("[{}] Sending route info about address {} to server {}", userId, address, serverId); - eventService.sendRouteInfo(new RouteInfo(tenantId, userId, address, ecfVersions), serverId); + LOG.debug("[{}] Sending route info about address {} to server {}", + userId, address, serverId); + eventService.sendRouteInfo(new RouteInfo( + tenantId, userId, address, ecfVersions), serverId); } } versionMap.put(address.getEndpointKey(), message.getEcfVersions()); @@ -266,8 +284,11 @@ protected String getActorPathName(ActorRef actorRef) { return actorRef.path().name(); } - private void addGlobalRoute(ActorContext context, EndpointUserConnectMessage message, RouteTableAddress address) { - GlobalRouteInfo route = GlobalRouteInfo.add(tenantId, userId, address, message.getCfVersion(), message.getUcfHash()); + private void addGlobalRoute(ActorContext context, + EndpointUserConnectMessage message, + RouteTableAddress address) { + GlobalRouteInfo route = GlobalRouteInfo.add( + tenantId, userId, address, message.getCfVersion(), message.getUcfHash()); localRoutes.put(address, route); sendGlobalRouteUpdate(context, route); } @@ -281,26 +302,35 @@ private void sendGlobalRouteUpdate(ActorContext context, GlobalRouteInfo route) } } - private void updateRouteTable(ActorContext context, RouteTableKey key, RouteTableAddress address) { - LOG.debug("[{}] adding to route table key: {} address: {}", userId, key, address); + private void updateRouteTable(ActorContext context, + RouteTableKey key, + RouteTableAddress address) { + LOG.debug("[{}] adding to route table key: {} address: {}", + userId, key, address); routeTable.add(key, address); sendPendingEvents(context, key, address); } - private void sendPendingEvents(ActorContext context, RouteTableKey key, RouteTableAddress address) { + private void sendPendingEvents(ActorContext context, + RouteTableKey key, + RouteTableAddress address) { List events = eventStorage.getEvents(key, address); if (events.size() > 0) { sendEventsToRecepient(context, address, events); } } - private void sendEventToRecepients(ActorContext context, EndpointEvent event, Collection recipients) { + private void sendEventToRecepients(ActorContext context, + EndpointEvent event, + Collection recipients) { for (RouteTableAddress recipient : recipients) { sendEventsToRecepient(context, recipient, Collections.singletonList(event)); } } - private void sendEventsToRecepient(ActorContext context, RouteTableAddress recipient, List events) { + private void sendEventsToRecepient(ActorContext context, + RouteTableAddress recipient, + List events) { List eventsToSend = new ArrayList<>(events.size()); for (EndpointEvent event : events) { if (!eventDeliveryTable.isDeliveryStarted(event, recipient)) { @@ -315,18 +345,22 @@ private void sendEventsToRecepient(ActorContext context, RouteTableAddress recip LOG.trace("[{}] forwarding event {} to local recepient {}", userId, event, recipient); } } - EndpointEventReceiveMessage message = new EndpointEventReceiveMessage(userId, eventsToSend, recipient, context.self()); + EndpointEventReceiveMessage message = new EndpointEventReceiveMessage( + userId, eventsToSend, recipient, context.self()); sendEventToLocal(context, message); } else { for (EndpointEvent event : eventsToSend) { - LOG.trace("[{}] forwarding event {} to remote recepient {}", userId, event, recipient); - RemoteEndpointEvent remoteEvent = new RemoteEndpointEvent(tenantId, userId, event, recipient); + LOG.trace("[{}] forwarding event {} to remote recepient {}", + userId, event, recipient); + RemoteEndpointEvent remoteEvent = new RemoteEndpointEvent( + tenantId, userId, event, recipient); eventService.sendEvent(remoteEvent); } } for (EndpointEvent event : eventsToSend) { - LOG.debug("[{}] registering delivery attempt of event {} to recepient {}", userId, event, recipient); + LOG.debug("[{}] registering delivery attempt of event {} to recepient {}", + userId, event, recipient); eventDeliveryTable.registerDeliveryAttempt(event, recipient); } } @@ -348,9 +382,11 @@ private void processEvent(ActorContext context, EndpointEvent event) { } if (version != null && version > 0) { event.setVersion(version); - Set recipientKeys = cacheService.getRouteKeys(new EventClassFqnVersion(tenantId, fqn, version)); + Set recipientKeys = cacheService.getRouteKeys( + new EventClassFqnVersion(tenantId, fqn, version)); if (!recipientKeys.isEmpty()) { - LOG.debug("[{}] Put event {} with {} recipient keys to storage", userId, event.getId(), recipientKeys.size()); + LOG.debug("[{}] Put event {} with {} recipient keys to storage", + userId, event.getId(), recipientKeys.size()); eventStorage.put(event, recipientKeys); Set recipients = routeTable.getRoutes(recipientKeys, event.getTarget()); @@ -360,12 +396,14 @@ private void processEvent(ActorContext context, EndpointEvent event) { if (!recipients.isEmpty()) { sendEventToRecepients(context, event, recipients); } else { - LOG.debug("[{}] there is no recipients for event with class fqn {} and version {} yet", userId, fqn, version); + LOG.debug("[{}] there is no recipients for event with class fqn {} and version {} yet", + userId, fqn, version); } scheduleTimeoutMessage(context, event); } else { - LOG.debug("[{}] event {} is ignored due to it does not have any potential recepients", userId, event.getId()); + LOG.debug("[{}] event {} is ignored due to it does not have any potential recepients", + userId, event.getId()); } } } @@ -373,17 +411,21 @@ private void processEvent(ActorContext context, EndpointEvent event) { protected Integer lookupVersion(EndpointEvent event, String fqn) { Integer version; LOG.debug("[{}] Lookup event class family id using event class fqn {}", userId, fqn); - String ecfId = cacheService.getEventClassFamilyIdByEventClassFqn(new EventClassFqnKey(tenantId, fqn)); + String ecfId = cacheService.getEventClassFamilyIdByEventClassFqn( + new EventClassFqnKey(tenantId, fqn)); - LOG.debug("[{}] Lookup event {} version from user's version map using ecfId {} ", userId, fqn, ecfId); + LOG.debug("[{}] Lookup event {} version from user's version map using ecfId {} ", + userId, fqn, ecfId); version = versionMap.get(event.getSender(), ecfId); if (version == null) { - LOG.warn("[{}] Lookup event {} version from user's version map using ecfId {} FAILED!", userId, fqn, ecfId); + LOG.warn("[{}] Lookup event {} version from user's version map using ecfId {} FAILED!", + userId, fqn, ecfId); } return version; } - protected Set filterOutRecipientsByKeyHash(EndpointEvent event, Set recipients) { + protected Set filterOutRecipientsByKeyHash( + EndpointEvent event, Set recipients) { Iterator recipientsIterator = recipients.iterator(); while (recipientsIterator.hasNext()) { RouteTableAddress recipient = recipientsIterator.next(); @@ -399,8 +441,10 @@ protected void removeEndpoint(ActorContext context, EndpointObjectHash endpoint) RouteTableAddress address = routeTable.removeLocal(endpoint); versionMap.remove(endpoint); for (String serverId : routeTable.getRemoteServers()) { - LOG.debug("[{}] removing endpoint [{}] from remote route table on server {}", userId, endpoint, serverId); - eventService.sendRouteInfo(RouteInfo.deleteRouteFromAddress(tenantId, userId, address), serverId); + LOG.debug("[{}] removing endpoint [{}] from remote route table on server {}", + userId, endpoint, serverId); + eventService.sendRouteInfo( + RouteInfo.deleteRouteFromAddress(tenantId, userId, address), serverId); } // cleanup and notify global route actor GlobalRouteInfo route = GlobalRouteInfo.delete(tenantId, userId, address); @@ -423,13 +467,16 @@ private void reportAllLocalRoutes(String serverId) { for (RouteTableKey routeKey : routeKeys) { ecfVersions.add(routeKey.getEcfVersion()); } - localRoutes.add(new RouteInfo(tenantId, userId, localAddress, new ArrayList<>(ecfVersions))); + localRoutes.add( + new RouteInfo(tenantId, userId, localAddress, new ArrayList<>(ecfVersions))); } else { - LOG.debug("[{}] Address {} is already delivered to serverId {} and will not be sent again", userId, localAddress, serverId); + LOG.debug("[{}] Address {} is already delivered to serverId {} and will not be sent again", + userId, localAddress, serverId); } } - LOG.debug("[{}] Reporting {}/{} local addresses/routes count", userId, localAddresses.size(), localRoutes.size()); + LOG.debug("[{}] Reporting {}/{} local addresses/routes count", + userId, localAddresses.size(), localRoutes.size()); if (!localRoutes.isEmpty()) { eventService.sendRouteInfo(localRoutes, serverId); routeTable.registerRouteInfoReport(localAddresses, serverId); @@ -439,11 +486,11 @@ private void reportAllLocalRoutes(String serverId) { void scheduleTimeoutMessage(ActorContext context, EndpointEvent event) { context.system() .scheduler() - .scheduleOnce(Duration.create(getTTL(event), TimeUnit.MILLISECONDS), context.self(), + .scheduleOnce(Duration.create(getTtl(event), TimeUnit.MILLISECONDS), context.self(), new EndpointEventTimeoutMessage(event), context.dispatcher(), context.self()); } - private long getTTL(EndpointEvent event) { + private long getTtl(EndpointEvent event) { return Math.max(eventTimeout - (System.currentTimeMillis() - event.getCreateTime()), 0L); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/io/EncDecActorMessageProcessor.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/io/EncDecActorMessageProcessor.java index aadb3f0263..bad5fa22dd 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/io/EncDecActorMessageProcessor.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/actors/io/EncDecActorMessageProcessor.java @@ -98,29 +98,37 @@ public class EncDecActorMessageProcessor { private final MeterClient redirectMeter; private final MeterClient errorMeter; - protected EncDecActorMessageProcessor(ActorRef epsActor, AkkaContext context, Set platformProtocols) { + protected EncDecActorMessageProcessor(ActorRef epsActor, + AkkaContext context, + Set platformProtocols) { super(); this.opsActor = epsActor; this.cacheService = context.getCacheService(); this.credentialsServiceLocator = context.getCredentialsServiceLocator(); this.registrationService = context.getRegistrationService(); this.supportUnencryptedConnection = context.getSupportUnencryptedConnection(); - this.crypt = new MessageEncoderDecoder(context.getKeyStoreService().getPrivateKey(), context.getKeyStoreService().getPublicKey()); + this.crypt = new MessageEncoderDecoder( + context.getKeyStoreService().getPrivateKey(), context.getKeyStoreService().getPublicKey()); this.platformEncDecMap = PlatformLookup.initPlatformProtocolMap(platformProtocols); MetricsService metricsService = context.getMetricsService(); - this.sessionInitMeter = metricsService.createMeter("sessionInitMeter", Thread.currentThread().getName()); - this.sessionRequestMeter = metricsService.createMeter("sessionRequestMeter", Thread.currentThread().getName()); - this.sessionResponseMeter = metricsService.createMeter("sessionResponseMeter", Thread.currentThread().getName()); - this.redirectMeter = metricsService.createMeter("redirectMeter", Thread.currentThread().getName()); - this.errorMeter = metricsService.createMeter("errorMeter", Thread.currentThread().getName()); + this.sessionInitMeter = metricsService.createMeter( + "sessionInitMeter", Thread.currentThread().getName()); + this.sessionRequestMeter = metricsService.createMeter( + "sessionRequestMeter", Thread.currentThread().getName()); + this.sessionResponseMeter = metricsService.createMeter( + "sessionResponseMeter", Thread.currentThread().getName()); + this.redirectMeter = metricsService.createMeter( + "redirectMeter", Thread.currentThread().getName()); + this.errorMeter = metricsService.createMeter( + "errorMeter", Thread.currentThread().getName()); } void decodeAndForward(ActorContext context, SessionInitMessage message) { try { sessionInitMeter.mark(); processSessionInitRequest(context, message); - } catch (Exception e) { - processErrors(message.getChannelContext(), message.getErrorBuilder(), e); + } catch (Exception ex) { + processErrors(message.getChannelContext(), message.getErrorBuilder(), ex); } } @@ -128,8 +136,8 @@ void decodeAndForward(ActorContext context, SessionAwareMessage message) { try { sessionRequestMeter.mark(); processSessionRequest(context, message); - } catch (Exception e) { - processErrors(message.getChannelContext(), message.getErrorBuilder(), e); + } catch (Exception ex) { + processErrors(message.getChannelContext(), message.getErrorBuilder(), ex); } } @@ -141,8 +149,8 @@ void encodeAndReply(SessionResponse message) { } else { processErrors(message.getChannelContext(), message.getErrorBuilder(), message.getError()); } - } catch (Exception e) { - processErrors(message.getChannelContext(), message.getErrorBuilder(), e); + } catch (Exception ex) { + processErrors(message.getChannelContext(), message.getErrorBuilder(), ex); } } @@ -151,7 +159,8 @@ public void forward(ActorContext context, SessionAware message) { LOG.debug("Forwarding session aware message: {}", message); this.opsActor.tell(message, context.self()); } else { - LOG.debug("Session aware message ignored. Reason: message {} has invalid sdk token", message); + LOG.debug("Session aware message ignored. Reason: message {} has invalid sdk token", + message); } } @@ -163,15 +172,18 @@ void redirect(RedirectionRule redirection, SessionInitMessage message) { EndpointObjectHash key = getEndpointObjectHash(request); String sdkToken = getSdkToken(request); String appToken = getAppToken(sdkToken); - SessionInfo sessionInfo = new SessionInfo(message.getChannelUuid(), message.getPlatformId(), message.getChannelContext(), - message.getChannelType(), crypt.getSessionCipherPair(), key, appToken, sdkToken, message.getKeepAlive(), + SessionInfo sessionInfo = new SessionInfo( + message.getChannelUuid(), message.getPlatformId(), message.getChannelContext(), + message.getChannelType(), crypt.getSessionCipherPair(), key, appToken, + sdkToken, message.getKeepAlive(), message.isEncrypted()); - SessionResponse responseMessage = new NettySessionResponseMessage(sessionInfo, response, message.getMessageBuilder(), + SessionResponse responseMessage = new NettySessionResponseMessage( + sessionInfo, response, message.getMessageBuilder(), message.getErrorBuilder()); LOG.debug("Redirect Response: {}", response); processSessionResponse(responseMessage); - } catch (Exception e) { - processErrors(message.getChannelContext(), message.getErrorBuilder(), e); + } catch (Exception ex) { + processErrors(message.getChannelContext(), message.getErrorBuilder(), ex); } } @@ -182,17 +194,19 @@ void redirect(RedirectionRule redirection, SessionAwareMessage message) { ClientSync request = decodeRequest(message); ServerSync response = buildRedirectionResponse(redirection, request); SessionInfo sessionInfo = message.getSessionInfo(); - SessionResponse responseMessage = new NettySessionResponseMessage(sessionInfo, response, message.getMessageBuilder(), + SessionResponse responseMessage = new NettySessionResponseMessage( + sessionInfo, response, message.getMessageBuilder(), message.getErrorBuilder()); LOG.debug("Redirect Response: {}", response); processSessionResponse(responseMessage); - } catch (Exception e) { - processErrors(message.getChannelContext(), message.getErrorBuilder(), e); + } catch (Exception ex) { + processErrors(message.getChannelContext(), message.getErrorBuilder(), ex); } } private ServerSync buildRedirectionResponse(RedirectionRule redirection, ClientSync request) { - RedirectServerSync redirectSyncResponse = new RedirectServerSync(redirection.getAccessPointId()); + RedirectServerSync redirectSyncResponse = new RedirectServerSync( + redirection.getAccessPointId()); ServerSync response = new ServerSync(); response.setRequestId(request.getRequestId()); response.setStatus(SyncStatus.REDIRECT); @@ -201,15 +215,18 @@ private ServerSync buildRedirectionResponse(RedirectionRule redirection, ClientS } private void processSessionInitRequest(ActorContext context, SessionInitMessage message) - throws GeneralSecurityException, PlatformEncDecException, InvalidSdkTokenException, EndpointVerificationException { + throws GeneralSecurityException, PlatformEncDecException, + InvalidSdkTokenException, EndpointVerificationException { ClientSync request = decodeRequest(message); EndpointObjectHash key = getEndpointObjectHash(request); String sdkToken = getSdkToken(request); if (isSDKTokenValid(sdkToken)) { String appToken = getAppToken(sdkToken); verifyEndpoint(key, appToken); - SessionInfo session = new SessionInfo(message.getChannelUuid(), message.getPlatformId(), message.getChannelContext(), - message.getChannelType(), crypt.getSessionCipherPair(), key, appToken, sdkToken, message.getKeepAlive(), + SessionInfo session = new SessionInfo( + message.getChannelUuid(), message.getPlatformId(), message.getChannelContext(), + message.getChannelType(), crypt.getSessionCipherPair(), key, + appToken, sdkToken, message.getKeepAlive(), message.isEncrypted()); message.onSessionCreated(session); forwardToOpsActor(context, session, request, message); @@ -219,7 +236,8 @@ private void processSessionInitRequest(ActorContext context, SessionInitMessage } } - private void verifyEndpoint(EndpointObjectHash key, String appToken) throws EndpointVerificationException { + private void verifyEndpoint(EndpointObjectHash key, String appToken) + throws EndpointVerificationException { // Credentials id match EP id in current implementation. // We will have two dedicated variables with same value just to // simplify reading of the logic. @@ -230,20 +248,25 @@ private void verifyEndpoint(EndpointObjectHash key, String appToken) throws Endp .findEndpointRegistrationByCredentialsId(credentialsId); if (!registrationLookupResult.isPresent()) { String appId = cacheService.getApplicationIdByAppToken(appToken); - CredentialsService credentialsService = credentialsServiceLocator.getCredentialsService(appId); + CredentialsService credentialsService = credentialsServiceLocator.getCredentialsService( + appId); - Optional credentailsLookupResult = credentialsService.lookupCredentials(credentialsId); + Optional credentailsLookupResult = credentialsService.lookupCredentials( + credentialsId); if (!credentailsLookupResult.isPresent()) { LOG.info("[{}] Credentials with id: [{}] not found!", appToken, credentialsId); - throw new EndpointVerificationException(EndpointVerificationError.NOT_FOUND, "Credentials not found!"); + throw new EndpointVerificationException( + EndpointVerificationError.NOT_FOUND, "Credentials not found!"); } CredentialsDto credentials = credentailsLookupResult.get(); if (credentials.getStatus() == CredentialsStatus.REVOKED) { LOG.info("[{}] Credentials with id: [{}] was already revoked!", appToken, credentialsId); - throw new EndpointVerificationException(EndpointVerificationError.REVOKED, "Credentials was revoked!"); + throw new EndpointVerificationException( + EndpointVerificationError.REVOKED, "Credentials was revoked!"); } else if (credentials.getStatus() == CredentialsStatus.IN_USE) { LOG.info("[{}] Credentials with id: [{}] are already in use!", appToken, credentialsId); - throw new EndpointVerificationException(EndpointVerificationError.IN_USE, "Credentials are already in use!"); + throw new EndpointVerificationException( + EndpointVerificationError.IN_USE, "Credentials are already in use!"); } else { credentialsService.markCredentialsInUse(credentialsId); EndpointRegistrationDto endpointRegistration = new EndpointRegistrationDto(); @@ -256,22 +279,27 @@ private void verifyEndpoint(EndpointObjectHash key, String appToken) throws Endp EndpointRegistrationDto endpointRegistration = registrationLookupResult.get(); if (endpointRegistration.getEndpointId() == null) { String appId = cacheService.getApplicationIdByAppToken(appToken); - CredentialsService credentialsService = credentialsServiceLocator.getCredentialsService(appId); + CredentialsService credentialsService = credentialsServiceLocator.getCredentialsService( + appId); credentialsService.markCredentialsInUse(credentialsId); endpointRegistration.setEndpointId(endpointId); registrationService.saveEndpointRegistration(endpointRegistration); } else if (!endpointId.equals(endpointRegistration.getEndpointId())) { - LOG.info("[{}] Credentials with id: [{}] are already in use!", appToken, credentialsId); - throw new EndpointVerificationException(EndpointVerificationError.IN_USE, "Credentials are already in use!"); + LOG.info("[{}] Credentials with id: [{}] are already in use!", + appToken, credentialsId); + throw new EndpointVerificationException(EndpointVerificationError.IN_USE, + "Credentials are already in use!"); } } - LOG.debug("[{}] Succesfully validated endpoint information: [{}]", appToken, credentialsId); - } catch (CredentialsServiceException e) { - LOG.info("[{}] Failed to lookup credentials info with id: [{}]", appToken, credentialsId, e); - throw new RuntimeException(e); - } catch (EndpointRegistrationServiceException e) { - LOG.info("[{}] Failed to lookup registration info with id: [{}]", appToken, credentialsId, e); - throw new RuntimeException(e); + LOG.debug("[{}] Succesfully validated endpoint information: [{}]", + appToken, credentialsId); + } catch (CredentialsServiceException ex) { + LOG.info("[{}] Failed to lookup credentials info with id: [{}]", appToken, credentialsId, ex); + throw new RuntimeException(ex); + } catch (EndpointRegistrationServiceException ex) { + LOG.info("[{}] Failed to lookup registration info with id: [{}]", + appToken, credentialsId, ex); + throw new RuntimeException(ex); } } @@ -286,12 +314,17 @@ private void processSessionRequest(ActorContext context, SessionAwareMessage mes } } - private void forwardToOpsActor(ActorContext context, SessionInfo session, ClientSync request, Message requestMessage) { - SyncRequestMessage message = new SyncRequestMessage(session, request, requestMessage, context.self()); + private void forwardToOpsActor(ActorContext context, + SessionInfo session, + ClientSync request, + Message requestMessage) { + SyncRequestMessage message = new SyncRequestMessage( + session, request, requestMessage, context.self()); this.opsActor.tell(message, context.self()); } - private void processSessionResponse(SessionResponse message) throws GeneralSecurityException, PlatformEncDecException { + private void processSessionResponse(SessionResponse message) + throws GeneralSecurityException, PlatformEncDecException { SessionInfo session = message.getSessionInfo(); byte[] responseData = encodePlatformLevelData(message.getPlatformId(), message); @@ -312,21 +345,26 @@ private void processSessionResponse(SessionResponse message) throws GeneralSecur } } - private ClientSync decodeRequest(SessionInitMessage message) throws GeneralSecurityException, PlatformEncDecException { + private ClientSync decodeRequest(SessionInitMessage message) + throws GeneralSecurityException, PlatformEncDecException { ClientSync syncRequest = null; if (message.isEncrypted()) { syncRequest = decodeEncryptedRequest(message); } else if (supportUnencryptedConnection) { syncRequest = decodeUnencryptedRequest(message); } else { - LOG.warn("Received unencrypted init message, but unencrypted connection forbidden by configuration."); + LOG.warn("Received unencrypted init message, " + + "but unencrypted connection forbidden by configuration."); throw new GeneralSecurityException("Unencrypted connection forbidden by configuration."); } return syncRequest; } - private ClientSync decodeEncryptedRequest(SessionInitMessage message) throws GeneralSecurityException, PlatformEncDecException { - byte[] requestRaw = crypt.decodeData(message.getEncodedMessageData(), message.getEncodedSessionKey()); + private ClientSync decodeEncryptedRequest(SessionInitMessage message) + throws GeneralSecurityException, PlatformEncDecException { + byte[] requestRaw = crypt.decodeData( + + message.getEncodedMessageData(), message.getEncodedSessionKey()); LOG.trace("Request data decrypted"); ClientSync request = decodePlatformLevelData(message.getPlatformId(), requestRaw); LOG.trace("Request data deserialized"); @@ -347,7 +385,8 @@ private ClientSync decodeEncryptedRequest(SessionInitMessage message) throws Gen return request; } - private ClientSync decodeUnencryptedRequest(SessionInitMessage message) throws GeneralSecurityException, PlatformEncDecException { + private ClientSync decodeUnencryptedRequest(SessionInitMessage message) + throws GeneralSecurityException, PlatformEncDecException { byte[] requestRaw = message.getEncodedMessageData(); LOG.trace("Try to convert raw data to SynRequest object"); ClientSync request = decodePlatformLevelData(message.getPlatformId(), requestRaw); @@ -362,7 +401,8 @@ private ClientSync decodeUnencryptedRequest(SessionInitMessage message) throws G return request; } - private ClientSync decodeEncryptedRequest(SessionAwareMessage message) throws GeneralSecurityException, PlatformEncDecException { + private ClientSync decodeEncryptedRequest(SessionAwareMessage message) + throws GeneralSecurityException, PlatformEncDecException { SessionInfo session = message.getSessionInfo(); crypt.setSessionCipherPair(session.getCipherPair()); byte[] requestRaw = crypt.decodeData(message.getEncodedMessageData()); @@ -372,41 +412,48 @@ private ClientSync decodeEncryptedRequest(SessionAwareMessage message) throws Ge return request; } - private ClientSync decodeUnencryptedRequest(SessionAwareMessage message) throws PlatformEncDecException { + private ClientSync decodeUnencryptedRequest(SessionAwareMessage message) + throws PlatformEncDecException { byte[] requestRaw = message.getEncodedMessageData(); ClientSync request = decodePlatformLevelData(message.getPlatformId(), requestRaw); LOG.trace("Request data deserialized"); return request; } - private byte[] encodePlatformLevelData(int platformID, SessionResponse message) throws PlatformEncDecException { + private byte[] encodePlatformLevelData(int platformID, SessionResponse message) + throws PlatformEncDecException { PlatformEncDec encDec = platformEncDecMap.get(platformID); if (encDec != null) { return platformEncDecMap.get(platformID).encode(message.getResponse()); } else { - throw new PlatformEncDecException(MessageFormat.format("Encoder for platform protocol [{0}] is not defined", platformID)); + throw new PlatformEncDecException( + MessageFormat.format("Encoder for platform protocol [{0}] is not defined", platformID)); } } - private ClientSync decodePlatformLevelData(Integer platformID, byte[] requestRaw) throws PlatformEncDecException { + private ClientSync decodePlatformLevelData(Integer platformID, byte[] requestRaw) + throws PlatformEncDecException { PlatformEncDec encDec = platformEncDecMap.get(platformID); if (encDec != null) { ClientSync syncRequest = platformEncDecMap.get(platformID).decode(requestRaw); addAppTokenToClientSyncMetaData(syncRequest.getClientSyncMetaData()); return syncRequest; } else { - throw new PlatformEncDecException(MessageFormat.format("Decoder for platform protocol [{0}] is not defined", platformID)); + throw new PlatformEncDecException( + MessageFormat.format("Decoder for platform protocol [{0}] is not defined", platformID)); } } - private ClientSync decodeRequest(SessionAwareMessage message) throws GeneralSecurityException, PlatformEncDecException { + private ClientSync decodeRequest(SessionAwareMessage message) + throws GeneralSecurityException, PlatformEncDecException { ClientSync syncRequest = null; if (message.isEncrypted()) { syncRequest = decodeEncryptedRequest(message); } else if (supportUnencryptedConnection) { syncRequest = decodeUnencryptedRequest(message); } else { - LOG.warn("Received unencrypted aware message, but unencrypted connection forbidden by configuration."); + LOG.warn("Received unencrypted aware message, " + + "but unencrypted connection forbidden by configuration."); throw new GeneralSecurityException("Unencrypted connection forbidden by configuration."); } return syncRequest; @@ -414,7 +461,8 @@ private ClientSync decodeRequest(SessionAwareMessage message) throws GeneralSecu private PublicKey getPublicKey(ClientSync request) throws GeneralSecurityException { PublicKey endpointKey = null; - if (request.getProfileSync() != null && request.getProfileSync().getEndpointPublicKey() != null) { + if (request.getProfileSync() != null + && request.getProfileSync().getEndpointPublicKey() != null) { byte[] publicKeySrc = request.getProfileSync().getEndpointPublicKey().array(); endpointKey = KeyUtil.getPublic(publicKeySrc); } @@ -425,16 +473,16 @@ private PublicKey getPublicKey(ClientSync request) throws GeneralSecurityExcepti return endpointKey; } - private void processErrors(ChannelContext ctx, ErrorBuilder converter, Exception e) { - LOG.trace("Request processing failed", e); + private void processErrors(ChannelContext ctx, ErrorBuilder converter, Exception ex) { + LOG.trace("Request processing failed", ex); errorMeter.mark(); - Object[] responses = converter.build(e); + Object[] responses = converter.build(ex); if (responses != null && responses.length > 0) { for (Object response : responses) { ctx.writeAndFlush(response); } } else { - ctx.fireExceptionCaught(e); + ctx.fireExceptionCaught(ex); } } @@ -455,6 +503,7 @@ private boolean isSDKTokenValid(String sdkToken) { } protected EndpointObjectHash getEndpointObjectHash(ClientSync request) { - return EndpointObjectHash.fromBytes(request.getClientSyncMetaData().getEndpointPublicKeyHash().array()); + return EndpointObjectHash.fromBytes( + request.getClientSyncMetaData().getEndpointPublicKeyHash().array()); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/endpoint/SyncRequestMessage.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/endpoint/SyncRequestMessage.java index 91d6c2323c..bd7e512978 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/endpoint/SyncRequestMessage.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/akka/messages/core/endpoint/SyncRequestMessage.java @@ -66,7 +66,10 @@ public class SyncRequestMessage extends EndpointAwareMessage implements ChannelA * @param requestMessage the request message * @param originator the originator */ - public SyncRequestMessage(SessionInfo session, ClientSync request, Message requestMessage, ActorRef originator) { + public SyncRequestMessage(SessionInfo session, + ClientSync request, + Message requestMessage, + ActorRef originator) { super(session.getApplicationToken(), session.getKey(), originator); this.command = requestMessage; this.request = request; @@ -131,17 +134,21 @@ public void updateRequest(ServerSync response) { public ClientSync merge(SyncRequestMessage syncRequest) { UUID channelUuid = getChannelUuid(); ClientSync other = syncRequest.getRequest(); - LOG.trace("[{}] Merging original request {} with new request {}", channelUuid, request, other); + LOG.trace("[{}] Merging original request {} with new request {}", + channelUuid, request, other); request.setRequestId(other.getRequestId()); - request.getClientSyncMetaData().setProfileHash(other.getClientSyncMetaData().getProfileHash()); + request.getClientSyncMetaData() + .setProfileHash(other.getClientSyncMetaData().getProfileHash()); LOG.debug("[{}] Updated request id and profile hash", channelUuid); ClientSync diff = new ClientSync(); diff.setRequestId(other.getRequestId()); diff.setClientSyncMetaData(other.getClientSyncMetaData()); diff.setUseConfigurationRawSchema(other.isUseConfigurationRawSchema()); if (request.getClientSyncMetaData().getApplicationToken() != null) { - LOG.debug("Setting application token, as it was null: {}", request.getClientSyncMetaData().getApplicationToken()); - diff.getClientSyncMetaData().setApplicationToken(request.getClientSyncMetaData().getApplicationToken()); + LOG.debug("Setting application token, as it was null: {}", + request.getClientSyncMetaData().getApplicationToken()); + diff.getClientSyncMetaData() + .setApplicationToken(request.getClientSyncMetaData().getApplicationToken()); } else { LOG.trace("[{}] Application token is null for request", request); } @@ -152,8 +159,10 @@ public ClientSync merge(SyncRequestMessage syncRequest) { LOG.debug("[{}] Updated profile request", channelUuid); } if (other.getConfigurationSync() != null) { - ConfigurationClientSync mergedConfigurationClientSync = hasProfileSync || other.isForceConfigurationSync() ? other - .getConfigurationSync() : diff(request.getConfigurationSync(), other.getConfigurationSync()); + ConfigurationClientSync mergedConfigurationClientSync = hasProfileSync + || other.isForceConfigurationSync() + ? other.getConfigurationSync() + : diff(request.getConfigurationSync(), other.getConfigurationSync()); diff.setConfigurationSync(mergedConfigurationClientSync); request.setConfigurationSync(other.getConfigurationSync()); LOG.debug("[{}] Updated configuration request", channelUuid); @@ -163,8 +172,10 @@ public ClientSync merge(SyncRequestMessage syncRequest) { } } if (other.getNotificationSync() != null) { - NotificationClientSync mergedNotificationClientSync = hasProfileSync || other.isForceNotificationSync() ? other - .getNotificationSync() : diff(request.getNotificationSync(), other.getNotificationSync()); + NotificationClientSync mergedNotificationClientSync = hasProfileSync + || other.isForceNotificationSync() + ? other.getNotificationSync() + : diff(request.getNotificationSync(), other.getNotificationSync()); diff.setNotificationSync(mergedNotificationClientSync); request.setNotificationSync(other.getNotificationSync()); LOG.debug("[{}] Updated notification request", channelUuid); @@ -191,11 +202,13 @@ public ClientSync merge(SyncRequestMessage syncRequest) { return diff; } - private ConfigurationClientSync diff(ConfigurationClientSync oldRequest, ConfigurationClientSync newRequest) { + private ConfigurationClientSync diff(ConfigurationClientSync oldRequest, + ConfigurationClientSync newRequest) { if (oldRequest == null) { return newRequest; } else { - if (!Arrays.equals(oldRequest.getConfigurationHash().array(), newRequest.getConfigurationHash().array())) { + if (!Arrays.equals(oldRequest.getConfigurationHash().array(), + newRequest.getConfigurationHash().array())) { return newRequest; } else { return null; @@ -203,12 +216,15 @@ private ConfigurationClientSync diff(ConfigurationClientSync oldRequest, Configu } } - private NotificationClientSync diff(NotificationClientSync oldRequest, NotificationClientSync newRequest) { + private NotificationClientSync diff(NotificationClientSync oldRequest, + NotificationClientSync newRequest) { if (oldRequest == null) { return newRequest; } else { - if ((newRequest.getAcceptedUnicastNotifications() != null && newRequest.getAcceptedUnicastNotifications().size() > 0) - || (newRequest.getSubscriptionCommands() != null && newRequest.getSubscriptionCommands().size() > 0) + if ((newRequest.getAcceptedUnicastNotifications() != null + && newRequest.getAcceptedUnicastNotifications().size() > 0) + || (newRequest.getSubscriptionCommands() != null + && newRequest.getSubscriptionCommands().size() > 0) || (newRequest.getTopicListHash() != oldRequest.getTopicListHash())) { return newRequest; } else { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/concurrent/ConcurrentCacheService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/concurrent/ConcurrentCacheService.java index c3927348b9..1fffbecf73 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/concurrent/ConcurrentCacheService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cache/concurrent/ConcurrentCacheService.java @@ -115,104 +115,151 @@ public class ConcurrentCacheService implements CacheService { /** * The app seq number memorizer. */ - private final CacheTemporaryMemorizer appSeqNumberMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer appSeqNumberMemorizer = + new CacheTemporaryMemorizer<>(); // /** * The cf id memorizer. */ - private final CacheTemporaryMemorizer cfIdMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer cfIdMemorizer = + new CacheTemporaryMemorizer<>(); /** * The history memorizer. */ - private final CacheTemporaryMemorizer> historyMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer> historyMemorizer = + new CacheTemporaryMemorizer<>(); /** * The filter lists memorizer. */ - private final CacheTemporaryMemorizer> filterListsMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer> filterListsMemorizer = + new CacheTemporaryMemorizer<>(); /** * The application event family maps memorizer. */ - private final CacheTemporaryMemorizer, List> aefmMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer, List> aefmMemorizer = + new CacheTemporaryMemorizer<>(); /** * The filters memorizer. */ - private final CacheTemporaryMemorizer filtersMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer filtersMemorizer = + new CacheTemporaryMemorizer<>(); /** * The cf memorizer. */ - private final CacheTemporaryMemorizer cfMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer cfMemorizer = + new CacheTemporaryMemorizer<>(); /** * The cf schema memorizer. */ - private final CacheTemporaryMemorizer cfSchemaMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer cfSchemaMemorizer = + new CacheTemporaryMemorizer<>(); /** * The pf schema memorizer. */ - private final CacheTemporaryMemorizer pfSchemaMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer pfSchemaMemorizer = + new CacheTemporaryMemorizer<>(); /** * The spf schema memorizer. */ - private final CacheTemporaryMemorizer spfSchemaMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer spfSchemaMemorizer = + new CacheTemporaryMemorizer<>(); /** * The ctl schema memorizer. */ - private final CacheTemporaryMemorizer ctlSchemaMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer ctlSchemaMemorizer = + new CacheTemporaryMemorizer<>(); /** * The ctl schema body memorizer. */ - private final CacheTemporaryMemorizer ctlSchemaBodyMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer ctlSchemaBodyMemorizer = + new CacheTemporaryMemorizer<>(); /** - * The SDK profile memorizer + * The SDK profile memorizer. */ - private final CacheTemporaryMemorizer sdkProfileMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer sdkProfileMemorizer = + new CacheTemporaryMemorizer<>(); /** * The endpoint key memorizer. */ - private final CacheTemporaryMemorizer endpointKeyMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer endpointKeyMemorizer = + new CacheTemporaryMemorizer<>(); /** * The merged configuration memorizer. */ - private final CacheTemporaryMemorizer, Pair> mergedConfigurationMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer, + Pair> mergedConfigurationMemorizer = new CacheTemporaryMemorizer<>(); /** * The delta memorizer. */ - private final CacheTemporaryMemorizer deltaMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer deltaMemorizer = + new CacheTemporaryMemorizer<>(); /** * The endpoint key memorizer. */ - private final CacheTemporaryMemorizer ecfIdKeyMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer ecfIdKeyMemorizer = + new CacheTemporaryMemorizer<>(); /** * The endpoint key memorizer. */ - private final CacheTemporaryMemorizer tenantIdMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer tenantIdMemorizer = + new CacheTemporaryMemorizer<>(); /** * The application token memorizer. */ - private final CacheTemporaryMemorizer appTokenMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer appTokenMemorizer = + new CacheTemporaryMemorizer<>(); /** * The endpoint groups memorizer. */ - private final CacheTemporaryMemorizer groupsMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer groupsMemorizer = + new CacheTemporaryMemorizer<>(); /** * The topics memorizer. */ - private final CacheTemporaryMemorizer topicsMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer topicsMemorizer = + new CacheTemporaryMemorizer<>(); /** * The default group memorizer. */ - private final CacheTemporaryMemorizer defaultGroupMemorizer = new CacheTemporaryMemorizer<>(); + private final CacheTemporaryMemorizer defaultGroupMemorizer = + new CacheTemporaryMemorizer<>(); /** * The topic list memorizer. */ - private final CacheTemporaryMemorizer topicListMemorizer = new CacheTemporaryMemorizer<>(); + private + final + CacheTemporaryMemorizer topicListMemorizer = + new CacheTemporaryMemorizer<>(); /** * The endpoint key memorizer. */ - private final CacheTemporaryMemorizer ecfIdFqnMemorizer = new CacheTemporaryMemorizer(); + private final CacheTemporaryMemorizer ecfIdFqnMemorizer = + new CacheTemporaryMemorizer<>(); /** * The endpoint key memorizer. */ - private final CacheTemporaryMemorizer> routeKeysMemorizer = new CacheTemporaryMemorizer>(); + private + final + CacheTemporaryMemorizer> routeKeysMemorizer = + new CacheTemporaryMemorizer<>(); /** * The application service. */ @@ -292,8 +339,11 @@ public AppSeqNumber getAppSeqNumber(String key) { public AppSeqNumber compute(String key) { LOG.debug("Fetching result for getAppSeqNumber"); ApplicationDto appDto = applicationService.findAppByApplicationToken(key); - AppSeqNumber appSeqNumber = new AppSeqNumber(appDto.getTenantId(), appDto.getId(), appDto.getApplicationToken(), appDto - .getSequenceNumber()); + AppSeqNumber appSeqNumber = new AppSeqNumber( + appDto.getTenantId(), + appDto.getId(), + appDto.getApplicationToken(), + appDto.getSequenceNumber()); return appSeqNumber; } }); @@ -326,7 +376,8 @@ public String getConfIdByKey(ConfigurationIdKey key) { public String compute(ConfigurationIdKey key) { LOG.debug("Fetching result for getConfIdByKey"); String confId = null; - List configurations = configurationService.findConfigurationsByEndpointGroupId(key.getEndpointGroupId()); + List configurations = + configurationService.findConfigurationsByEndpointGroupId(key.getEndpointGroupId()); for (ConfigurationDto confDto : configurations) { if (confDto.getSchemaVersion() == key.getConfigSchemaVersion()) { confId = confDto.getId(); @@ -369,7 +420,8 @@ public List compute(HistoryKey key) { List relatedChanges = new ArrayList(); ApplicationDto appDto = applicationService.findAppByApplicationToken(key.getAppToken()); - List fullHistoryList = historyService.findHistoriesBySeqNumberRange(appDto.getId(), key.getOldSeqNumber(), + List fullHistoryList = historyService.findHistoriesBySeqNumberRange( + appDto.getId(), key.getOldSeqNumber(), key.getNewSeqNumber()); Collections.sort(fullHistoryList, ConcurrentCacheService.HISTORY_SEQ_NUMBER_COMPARATOR); @@ -384,8 +436,12 @@ public List compute(HistoryKey key) { } else if (changeType == ChangeType.ADD_TOPIC || changeType == ChangeType.REMOVE_TOPIC) { relatedChanges.add(historyDto); } else if (changeType == ChangeType.ADD_PROF || changeType == ChangeType.REMOVE_PROF) { - ProfileFilterDto profileFilter = profileService.findProfileFilterById(changeDto.getProfileFilterId()); - if (profileFilter != null && supports(profileFilter, key.getEndpointProfileSchemaVersion(), key.getServerProfileSchemaVersion())) { + ProfileFilterDto profileFilter = profileService.findProfileFilterById( + changeDto.getProfileFilterId()); + if (profileFilter != null + && supports(profileFilter, + key.getEndpointProfileSchemaVersion(), + key.getServerProfileSchemaVersion())) { relatedChanges.add(historyDto); } } else if (changeType == ChangeType.ADD_CONF || changeType == ChangeType.REMOVE_CONF) { @@ -398,9 +454,13 @@ public List compute(HistoryKey key) { return relatedChanges; } - private boolean supports(ProfileFilterDto profileFilter, Integer endpointProfileSchemaVersion, Integer serverProfileSchemaVersion) { - return (profileFilter.getEndpointProfileSchemaVersion() == null || profileFilter.getEndpointProfileSchemaVersion() == endpointProfileSchemaVersion) - && (profileFilter.getServerProfileSchemaVersion() == null || profileFilter.getServerProfileSchemaVersion() == serverProfileSchemaVersion); + private boolean supports(ProfileFilterDto profileFilter, + Integer endpointProfileSchemaVersion, + Integer serverProfileSchemaVersion) { + return (profileFilter.getEndpointProfileSchemaVersion() == null + || profileFilter.getEndpointProfileSchemaVersion() == endpointProfileSchemaVersion) + && (profileFilter.getServerProfileSchemaVersion() == null + || profileFilter.getServerProfileSchemaVersion() == serverProfileSchemaVersion); } }); } @@ -422,20 +482,23 @@ public List putHistory(HistoryKey key, List value) { @Override @Cacheable("applicationEFMs") public List getApplicationEventFamilyMapsByIds(List key) { - return aefmMemorizer.compute(key, new Computable, List>() { - @Override - public List compute(List key) { - LOG.debug("Fetching result for getApplicationEventFamilyMapsByIds"); - List value = applicationEventMapService.findApplicationEventFamilyMapsByIds(key); - putApplicationEventFamilyMaps(key, value); - return value; - } - }); + return aefmMemorizer.compute(key, + new Computable, List>() { + @Override + public List compute(List key) { + LOG.debug("Fetching result for getApplicationEventFamilyMapsByIds"); + List value = + applicationEventMapService.findApplicationEventFamilyMapsByIds(key); + putApplicationEventFamilyMaps(key, value); + return value; + } + }); } @Override @CachePut(value = "applicationEFMs", key = "#key") - public List putApplicationEventFamilyMaps(List key, List value) { + public List putApplicationEventFamilyMaps( + List key, List value) { return value; } @@ -449,17 +512,20 @@ public List putApplicationEventFamilyMaps(List getFilters(AppProfileVersionsKey key) { - return filterListsMemorizer.compute(key, new Computable>() { - - @Override - public List compute(AppProfileVersionsKey key) { - LOG.debug("Fetching result for getFilters"); - ApplicationDto appDto = applicationService.findAppByApplicationToken(key.getApplicationToken()); - List value = profileService.findProfileFiltersByAppIdAndVersionsCombination(appDto.getId(), - key.getEndpointProfileSchemaVersion(), key.getServerProfileSchemaVersion()); - return value; - } - }); + return filterListsMemorizer.compute(key, + new Computable>() { + + @Override + public List compute(AppProfileVersionsKey key) { + LOG.debug("Fetching result for getFilters"); + ApplicationDto appDto = applicationService.findAppByApplicationToken( + key.getApplicationToken()); + List value = + profileService.findProfileFiltersByAppIdAndVersionsCombination(appDto.getId(), + key.getEndpointProfileSchemaVersion(), key.getServerProfileSchemaVersion()); + return value; + } + }); } /* @@ -485,7 +551,8 @@ public void resetFilters(AppProfileVersionsKey key) { */ @Override @CachePut(value = "filterLists", key = "#key") - public List putFilterList(AppProfileVersionsKey key, List value) { + public List putFilterList(AppProfileVersionsKey key, + List value) { return value; } @@ -533,15 +600,17 @@ public ProfileFilterDto putFilter(String key, ProfileFilterDto value) { @Override @Cacheable("configurations") public EndpointConfigurationDto getConfByHash(EndpointObjectHash key) { - return cfMemorizer.compute(key, new Computable() { - - @Override - public EndpointConfigurationDto compute(EndpointObjectHash key) { - LOG.debug("Fetching result for getConfByHash {}", key); - EndpointConfigurationDto value = endpointService.findEndpointConfigurationByHash(key.getData()); - return value; - } - }); + return cfMemorizer.compute(key, + new Computable() { + + @Override + public EndpointConfigurationDto compute(EndpointObjectHash key) { + LOG.debug("Fetching result for getConfByHash {}", key); + EndpointConfigurationDto value = endpointService.findEndpointConfigurationByHash( + key.getData()); + return value; + } + }); } /* @@ -553,7 +622,8 @@ public EndpointConfigurationDto compute(EndpointObjectHash key) { */ @Override @CachePut(value = "configurations", key = "#key") - public EndpointConfigurationDto putConfiguration(EndpointObjectHash key, EndpointConfigurationDto value) { + public EndpointConfigurationDto putConfiguration(EndpointObjectHash key, + EndpointConfigurationDto value) { if (value != null) { LOG.debug("Fetching result for getConfByHash"); value = endpointService.saveEndpointConfiguration(value); @@ -571,16 +641,19 @@ public EndpointConfigurationDto putConfiguration(EndpointObjectHash key, Endpoin @Override @Cacheable("configurationSchemas") public ConfigurationSchemaDto getConfSchemaByAppAndVersion(AppVersionKey key) { - return cfSchemaMemorizer.compute(key, new Computable() { - - @Override - public ConfigurationSchemaDto compute(AppVersionKey key) { - LOG.debug("Fetching result for getConfSchemaByAppAndVersion"); - ApplicationDto appDto = applicationService.findAppByApplicationToken(key.getApplicationToken()); - ConfigurationSchemaDto value = configurationService.findConfSchemaByAppIdAndVersion(appDto.getId(), key.getVersion()); - return value; - } - }); + return cfSchemaMemorizer.compute(key, + new Computable() { + + @Override + public ConfigurationSchemaDto compute(AppVersionKey key) { + LOG.debug("Fetching result for getConfSchemaByAppAndVersion"); + ApplicationDto appDto = applicationService.findAppByApplicationToken( + key.getApplicationToken()); + ConfigurationSchemaDto value = configurationService.findConfSchemaByAppIdAndVersion( + appDto.getId(), key.getVersion()); + return value; + } + }); } /* @@ -593,7 +666,8 @@ public ConfigurationSchemaDto compute(AppVersionKey key) { */ @Override @CachePut(value = "configurationSchemas", key = "#key") - public ConfigurationSchemaDto putConfigurationSchema(AppVersionKey key, ConfigurationSchemaDto value) { + public ConfigurationSchemaDto putConfigurationSchema(AppVersionKey key, + ConfigurationSchemaDto value) { return value; } @@ -607,32 +681,38 @@ public ConfigurationSchemaDto putConfigurationSchema(AppVersionKey key, Configur @Override @Cacheable("endpointProfileSchemas") public EndpointProfileSchemaDto getProfileSchemaByAppAndVersion(AppVersionKey key) { - return pfSchemaMemorizer.compute(key, new Computable() { - - @Override - public EndpointProfileSchemaDto compute(AppVersionKey key) { - LOG.debug("Fetching result for getProfileSchemaByAppAndVersion"); - ApplicationDto appDto = applicationService.findAppByApplicationToken(key.getApplicationToken()); - EndpointProfileSchemaDto value = profileService.findProfileSchemaByAppIdAndVersion(appDto.getId(), key.getVersion()); - return value; - } - }); + return pfSchemaMemorizer.compute(key, + new Computable() { + + @Override + public EndpointProfileSchemaDto compute(AppVersionKey key) { + LOG.debug("Fetching result for getProfileSchemaByAppAndVersion"); + ApplicationDto appDto = applicationService.findAppByApplicationToken( + key.getApplicationToken()); + EndpointProfileSchemaDto value = profileService.findProfileSchemaByAppIdAndVersion( + appDto.getId(), key.getVersion()); + return value; + } + }); } @Override @Cacheable("serverProfileSchemas") public ServerProfileSchemaDto getServerProfileSchemaByAppAndVersion(AppVersionKey key) { - return spfSchemaMemorizer.compute(key, new Computable() { - - @Override - public ServerProfileSchemaDto compute(AppVersionKey key) { - LOG.debug("Fetching result for getServerProfileSchemaByAppAndVersion"); - ApplicationDto appDto = applicationService.findAppByApplicationToken(key.getApplicationToken()); - ServerProfileSchemaDto value = serverProfileService.findServerProfileSchemaByAppIdAndVersion(appDto.getId(), - key.getVersion()); - return value; - } - }); + return spfSchemaMemorizer.compute(key, + new Computable() { + + @Override + public ServerProfileSchemaDto compute(AppVersionKey key) { + LOG.debug("Fetching result for getServerProfileSchemaByAppAndVersion"); + ApplicationDto appDto = applicationService.findAppByApplicationToken( + key.getApplicationToken()); + ServerProfileSchemaDto value = + serverProfileService.findServerProfileSchemaByAppIdAndVersion(appDto.getId(), + key.getVersion()); + return value; + } + }); } @Override @@ -670,7 +750,8 @@ public String compute(String key) { */ @Override @CachePut(value = "endpointProfileSchemas", key = "#key") - public EndpointProfileSchemaDto putProfileSchema(AppVersionKey key, EndpointProfileSchemaDto value) { + public EndpointProfileSchemaDto putProfileSchema(AppVersionKey key, + EndpointProfileSchemaDto value) { return value; } @@ -701,14 +782,16 @@ public PublicKey getEndpointKey(EndpointObjectHash key) { public PublicKey compute(EndpointObjectHash key) { LOG.debug("Fetching result for getEndpointKey"); PublicKey result = null; - EndpointProfileDto endpointProfile = endpointService.findEndpointProfileByKeyHash(key.getData()); + EndpointProfileDto endpointProfile = endpointService.findEndpointProfileByKeyHash( + key.getData()); if (endpointProfile != null) { try { - X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(endpointProfile.getEndpointKey()); + X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec( + endpointProfile.getEndpointKey()); KeyFactory keyFact = KeyFactory.getInstance(ALGORITHM); result = keyFact.generatePublic(x509KeySpec); - } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { - LOG.error("failed to decode key", e); + } catch (NoSuchAlgorithmException | InvalidKeySpecException ex) { + LOG.error("failed to decode key", ex); } } else { LOG.error("failed to find key by hash {}", key); @@ -726,11 +809,13 @@ public String getEventClassFamilyIdByName(EventClassFamilyIdKey key) { @Override public String compute(EventClassFamilyIdKey key) { LOG.debug("Fetching result for getEcfvId using key {}", key); - EventClassFamilyDto ecf = eventClassService.findEventClassFamilyByTenantIdAndName(key.getTenantId(), key.getName()); + EventClassFamilyDto ecf = eventClassService.findEventClassFamilyByTenantIdAndName( + key.getTenantId(), key.getName()); if (ecf != null) { return ecf.getId(); } else { - LOG.error("failed to find ecf by tenantId [{}] and name {}", key.getTenantId(), key.getName()); + LOG.error("failed to find ecf by tenantId [{}] and name {}", + key.getTenantId(), key.getName()); return null; } } @@ -745,7 +830,8 @@ public String getEventClassFamilyIdByEventClassFqn(EventClassFqnKey key) { @Override public String compute(EventClassFqnKey key) { LOG.debug("Fetching result for getEventClassFamilyIdByEventClassFqn using key {}", key); - List eventClasses = eventClassService.findEventClassByTenantIdAndFQN(key.getTenantId(), key.getFqn()); + List eventClasses = eventClassService.findEventClassByTenantIdAndFQN( + key.getTenantId(), key.getFqn()); if (eventClasses != null && !eventClasses.isEmpty()) { String ecfvId = eventClasses.get(0).getEcfvId(); return eventClassService.findEventClassFamilyByEcfvId(ecfvId).getId(); @@ -761,40 +847,44 @@ public String compute(EventClassFqnKey key) { @Override @Cacheable("routeKeys") public Set getRouteKeys(EventClassFqnVersion key) { - return routeKeysMemorizer.compute(key, new Computable>() { - - @Override - public Set compute(EventClassFqnVersion key) { - LOG.debug("Fetching result for getRouteKeys using key {}", key); - Set routeKeys = new HashSet<>(); - EventClassDto eventClass = eventClassService.findEventClassByTenantIdAndFQNAndVersion(key.getTenantId(), key.getFqn(), - key.getVersion()); - - String ecfvId = eventClass.getEcfvId(); - String ecfId = eventClassService.findEventClassFamilyByEcfvId(ecfvId).getId(); - - List mappingList = applicationEventMapService.findByEcfIdAndVersion(ecfId, - key.getVersion()); - for (ApplicationEventFamilyMapDto mapping : mappingList) { - String applicationId = mapping.getApplicationId(); - ApplicationDto appDto = applicationService.findAppById(applicationId); - RouteTableKey routeTableKey = new RouteTableKey(appDto.getApplicationToken(), new EventClassFamilyVersion( - ecfId, key.getVersion())); - if (!routeKeys.contains(routeTableKey)) { - for (ApplicationEventMapDto eventMap : mapping.getEventMaps()) { - if (eventMap.getEventClassId().equals(eventClass.getId()) - && (ApplicationEventAction.SINK == eventMap.getAction() || ApplicationEventAction.BOTH == eventMap - .getAction())) { - routeKeys.add(routeTableKey); - break; + return routeKeysMemorizer.compute(key, + new Computable>() { + + @Override + public Set compute(EventClassFqnVersion key) { + LOG.debug("Fetching result for getRouteKeys using key {}", key); + Set routeKeys = new HashSet<>(); + EventClassDto eventClass = eventClassService.findEventClassByTenantIdAndFQNAndVersion( + key.getTenantId(), key.getFqn(), + key.getVersion()); + + String ecfvId = eventClass.getEcfvId(); + String ecfId = eventClassService.findEventClassFamilyByEcfvId(ecfvId).getId(); + + List mappingList = + applicationEventMapService.findByEcfIdAndVersion(ecfId, + key.getVersion()); + for (ApplicationEventFamilyMapDto mapping : mappingList) { + String applicationId = mapping.getApplicationId(); + ApplicationDto appDto = applicationService.findAppById(applicationId); + RouteTableKey routeTableKey = new RouteTableKey( + appDto.getApplicationToken(), new EventClassFamilyVersion( + ecfId, key.getVersion())); + if (!routeKeys.contains(routeTableKey)) { + for (ApplicationEventMapDto eventMap : mapping.getEventMaps()) { + if (eventMap.getEventClassId().equals(eventClass.getId()) + && (ApplicationEventAction.SINK == eventMap.getAction() + || ApplicationEventAction.BOTH == eventMap.getAction())) { + routeKeys.add(routeTableKey); + break; + } + } } } - } - } - return routeKeys; - } - }); + return routeKeys; + } + }); } @Override @@ -870,7 +960,7 @@ public PublicKey putEndpointKey(EndpointObjectHash key, PublicKey endpointKey) { } /** - * Remove key from hash + * Remove key from hash. */ @Override @CacheEvict(value = "endpointKeys", key = "#key") @@ -887,16 +977,19 @@ public void resetEndpointKey(EndpointObjectHash hash, PublicKey endpointKey) { */ @Override @Cacheable(value = "mergedConfigurations", key = "#key") - public Pair getMergedConfiguration(final List key, - final Computable, Pair> worker) { - return mergedConfigurationMemorizer.compute(key, new Computable, Pair>() { - @Override - public Pair compute(List key) { - LOG.debug("Fetching result for getMergedConfiguration"); - Pair result = worker.compute(key); - return result; - } - }); + public Pair getMergedConfiguration( + final List key, + final Computable, + Pair> worker) { + return mergedConfigurationMemorizer.compute(key, + new Computable, Pair>() { + @Override + public Pair compute(List key) { + LOG.debug("Fetching result for getMergedConfiguration"); + Pair result = worker.compute(key); + return result; + } + }); } /* @@ -907,7 +1000,8 @@ public Pair compute(List key) { */ @Override @CachePut(value = "mergedConfigurations", key = "#key") - public BaseData setMergedConfiguration(List key, BaseData mergedConfiguration) { + public BaseData setMergedConfiguration(List key, + BaseData mergedConfiguration) { return mergedConfiguration; } @@ -921,16 +1015,19 @@ public BaseData setMergedConfiguration(List key, BaseData */ @Override @Cacheable(value = "deltas", key = "#key") - public ConfigurationCacheEntry getDelta(final DeltaCacheKey key, final Computable worker) + public ConfigurationCacheEntry getDelta(final DeltaCacheKey key, + final Computable worker) throws GetDeltaException { - ConfigurationCacheEntry deltaCacheEntry = deltaMemorizer.compute(key, new Computable() { // NOSONAR - @Override - public ConfigurationCacheEntry compute(DeltaCacheKey key) { - LOG.debug("Fetching result for getMergedConfiguration"); - ConfigurationCacheEntry result = worker.compute(key); - return result; - } - }); + ConfigurationCacheEntry deltaCacheEntry = deltaMemorizer.compute(key, + new Computable() { // NOSONAR + @Override + public ConfigurationCacheEntry compute(DeltaCacheKey key) { + LOG.debug("Fetching result for getMergedConfiguration"); + ConfigurationCacheEntry result = worker.compute(key); + return result; + } + }); return deltaCacheEntry; } @@ -1008,7 +1105,8 @@ public EndpointGroupDto getDefaultGroup(String applicationToken) { @CachePut(value = "topicListEntries", key = "#key") public TopicListCacheEntry putTopicList(EndpointObjectHash key, TopicListCacheEntry entry) { if (entry != null) { - TopicListEntryDto entryDto = new TopicListEntryDto(entry.getSimpleHash(), entry.getHash().getData(), entry.getTopics()); + TopicListEntryDto entryDto = new TopicListEntryDto( + entry.getSimpleHash(), entry.getHash().getData(), entry.getTopics()); endpointService.saveTopicListEntry(entryDto); } return entry; @@ -1017,18 +1115,22 @@ public TopicListCacheEntry putTopicList(EndpointObjectHash key, TopicListCacheEn @Override @Cacheable("topicListEntries") public TopicListCacheEntry getTopicListByHash(EndpointObjectHash hash) { - return topicListMemorizer.compute(hash, new Computable() { - @Override - public TopicListCacheEntry compute(EndpointObjectHash key) { - LOG.debug("Fetching result for getTopicListByHash {}", key); - TopicListEntryDto entryDto = endpointService.findTopicListEntryByHash(key.getData()); - if (entryDto != null) { - return new TopicListCacheEntry(entryDto.getSimpleHash(), EndpointObjectHash.fromBytes(entryDto.getHash()), entryDto.getTopics()); - } else { - return null; - } - } - }); + return topicListMemorizer.compute(hash, + new Computable() { + @Override + public TopicListCacheEntry compute(EndpointObjectHash key) { + LOG.debug("Fetching result for getTopicListByHash {}", key); + TopicListEntryDto entryDto = endpointService.findTopicListEntryByHash(key.getData()); + if (entryDto != null) { + return new TopicListCacheEntry( + entryDto.getSimpleHash(), + EndpointObjectHash.fromBytes(entryDto.getHash()), + entryDto.getTopics()); + } else { + return null; + } + } + }); } /* @@ -1094,7 +1196,8 @@ public void setEventClassService(EventClassService eventClassService) { } @Override - public void setApplicationEventMapService(ApplicationEventMapService applicationEventMapService) { + public void setApplicationEventMapService( + ApplicationEventMapService applicationEventMapService) { this.applicationEventMapService = applicationEventMapService; } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/ClusterService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/ClusterService.java index ed889f0dfc..15bccb0e30 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/ClusterService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/ClusterService.java @@ -52,7 +52,7 @@ public interface ClusterService { void setListener(ClusterServiceListener listener); /** - * Returns id of the current node + * Returns id of the current node. * * @return id of the current node */ @@ -60,7 +60,7 @@ public interface ClusterService { /** * Checks if global entity actor for specified entity is located on current - * node + * node. * * @param entityId to check * @return true if global entity actor is located on this node, false otherwise. @@ -69,15 +69,15 @@ public interface ClusterService { /** * Checks if global entity actor for specified entity is located on current - * node + * node. * - * @param entityId to check + * @param entityId to check. * @return true if global entity actor is located on this node, false otherwise. */ boolean isMainEntityNode(byte[] entityId); /** - * Returns id of the node that should contain global entity actor + * Returns id of the node that should contain global entity actor. * * @param entityId the entity id * @return id of the global entity actor node @@ -85,7 +85,7 @@ public interface ClusterService { String getEntityNode(EndpointObjectHash entityId); /** - * Returns id of the node that should contain global entity actor + * Returns id of the node that should contain global entity actor. * * @param entityId the entity id * @return id of the global entity actor node @@ -101,7 +101,7 @@ public interface ClusterService { String sendRouteMessage(EndpointRouteMessage msg); /** - * Send unicast notification message to specified node + * Send unicast notification message to specified node. * * @param nodeId - id of the server node * @param msg the unicast notification message @@ -109,7 +109,7 @@ public interface ClusterService { void sendUnicastNotificationMessage(String nodeId, ThriftUnicastNotificationMessage msg); /** - * Send server profile update message to specified node + * Send server profile update message to specified node. * * @param nodeId - id of the server node * @param msg the unicast notification message @@ -117,28 +117,28 @@ public interface ClusterService { void sendServerProfileUpdateMessage(String nodeId, ThriftServerProfileUpdateMessage msg); /** - * Process entity route messages + * Process entity route messages. * * @param msgs the entity route messages */ void onEntityRouteMessages(List msgs); /** - * Process unicast notification message + * Process unicast notification message. * * @param msg the unicast notification message */ void onUnicastNotificationMessage(ThriftUnicastNotificationMessage msg); /** - * Process server profile update message + * Process server profile update message. * * @param msg the server profile update message */ void onServerProfileUpdateMessage(ThriftServerProfileUpdateMessage msg); /** - * Process endpoint de-registration message + * Process endpoint de-registration message. * * @param msg the endpoint de-registration message */ diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/ClusterServiceListener.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/ClusterServiceListener.java index f68b7e8918..b5bee3b973 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/ClusterServiceListener.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/ClusterServiceListener.java @@ -29,7 +29,7 @@ public interface ClusterServiceListener { void onRouteMsg(EndpointRouteMessage msg); /** - * Process endpoint actor message + * Process endpoint actor message. * * @param msg the endpoint actor message */ @@ -37,7 +37,7 @@ public interface ClusterServiceListener { /** - * Reports update of cluster topology; + * Reports update of cluster topology. */ void onClusterUpdated(); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/DefaultClusterService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/DefaultClusterService.java index 4a85ad20fe..a353692ff4 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/DefaultClusterService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/cluster/DefaultClusterService.java @@ -70,7 +70,7 @@ public class DefaultClusterService implements ClusterService { private OperationsServerConfig operationsServerConfig; /** - * ID is thriftHost:thriftPort + * ID is thriftHost:thriftPort. */ private volatile String id; @@ -89,7 +89,7 @@ public DefaultClusterService() { @PostConstruct public void initBean() { LOG.info("Init default cluster service."); - neighbors = new Neighbors(KaaThriftService.OPERATIONS_SERVICE, new MessageTemplate(), + neighbors = new Neighbors<>(KaaThriftService.OPERATIONS_SERVICE, new MessageTemplate(), operationsServerConfig.getMaxNumberNeighborConnections()); } @@ -111,7 +111,10 @@ public String getNodeId() { public void setZkNode(OperationsNode operationsNode) { this.operationsNode = operationsNode; this.id = Neighbors.getServerId(this.operationsNode.getNodeInfo().getConnectionInfo()); - neighbors.setZkNode(KaaThriftService.OPERATIONS_SERVICE, this.operationsNode.getNodeInfo().getConnectionInfo(), operationsNode); + neighbors.setZkNode( + KaaThriftService.OPERATIONS_SERVICE, + this.operationsNode.getNodeInfo().getConnectionInfo(), + operationsNode); if (resolver != null) { updateResolver(this.resolver); } @@ -204,17 +207,22 @@ public String sendRouteMessage(EndpointRouteMessage msg) { } @Override - public void sendUnicastNotificationMessage(String serverId, ThriftUnicastNotificationMessage msg) { + public void sendUnicastNotificationMessage(String serverId, + ThriftUnicastNotificationMessage msg) { sendServerProfileUpdateMessage(serverId, OperationsServiceMsg.fromNotification(msg)); } @Override - public void sendServerProfileUpdateMessage(String serverId, ThriftServerProfileUpdateMessage msg) { - sendServerProfileUpdateMessage(serverId, OperationsServiceMsg.fromServerProfileUpdateMessage(msg)); + public void sendServerProfileUpdateMessage(String serverId, + ThriftServerProfileUpdateMessage msg) { + sendServerProfileUpdateMessage( + serverId, OperationsServiceMsg.fromServerProfileUpdateMessage(msg)); } - private void sendServerProfileUpdateMessage(String serverId, OperationsServiceMsg msg) { - NeighborConnection server = neighbors.getNeghborConnection(serverId); + private void sendServerProfileUpdateMessage(String serverId, + OperationsServiceMsg msg) { + NeighborConnection server = + neighbors.getNeghborConnection(serverId); if (server == null) { LOG.warn("Specified server {} not found in neighbors list", serverId); } else { @@ -239,25 +247,38 @@ public void onEntityRouteMessages(List msgs) { public void onUnicastNotificationMessage(ThriftUnicastNotificationMessage msg) { EndpointAddress address = fromThriftAddress(msg.getAddress()); ActorClassifier classifier = fromThriftActorClassifier(msg.getActorClassifier()); - listener.onEndpointActorMsg(new ThriftEndpointActorMsg(address, classifier, msg)); + listener.onEndpointActorMsg(new ThriftEndpointActorMsg<>(address, classifier, msg)); } @Override public void onServerProfileUpdateMessage(ThriftServerProfileUpdateMessage msg) { EndpointAddress address = fromThriftAddress(msg.getAddress()); ActorClassifier classifier = fromThriftActorClassifier(msg.getActorClassifier()); - listener.onEndpointActorMsg(new ThriftEndpointActorMsg(address, classifier, msg)); + listener.onEndpointActorMsg(new ThriftEndpointActorMsg<>(address, classifier, msg)); } @Override public void onEndpointDeregistrationMessage(ThriftEndpointDeregistrationMessage msg) { EndpointAddress address = fromThriftAddress(msg.getAddress()); ActorClassifier classifier = fromThriftActorClassifier(msg.getActorClassifier()); - listener.onEndpointActorMsg(new ThriftEndpointActorMsg(address, classifier, msg)); + listener.onEndpointActorMsg(new ThriftEndpointActorMsg<>(address, classifier, msg)); } private EndpointAddress fromThriftAddress(ThriftEntityAddress source) { - return new EndpointAddress(source.getTenantId(), source.getApplicationToken(), EndpointObjectHash.fromBytes(source.getEntityId())); + return new EndpointAddress( + source.getTenantId(), + source.getApplicationToken(), + EndpointObjectHash.fromBytes(source.getEntityId())); + } + + private EndpointClusterAddress fromThriftAddress(ThriftEntityClusterAddress source) { + ThriftEntityAddress address = source.getAddress(); + EndpointObjectHash endpointKey = EndpointObjectHash.fromBytes(address.getEntityId()); + return new EndpointClusterAddress( + source.getNodeId(), + address.getTenantId(), + address.getApplicationToken(), + endpointKey); } private ActorClassifier fromThriftActorClassifier(ThriftActorClassifier actorClassifier) { @@ -265,7 +286,9 @@ private ActorClassifier fromThriftActorClassifier(ThriftActorClassifier actorCla } private EndpointRouteMessage fromThriftMsg(ThriftEntityRouteMessage source) { - return new EndpointRouteMessage(fromThriftAddress(source.getAddress()), fromThriftOperation(source.getOperation())); + return new EndpointRouteMessage( + fromThriftAddress(source.getAddress()), + fromThriftOperation(source.getOperation())); } private RouteOperation fromThriftOperation(ThriftRouteOperation operation) { @@ -281,19 +304,14 @@ private RouteOperation fromThriftOperation(ThriftRouteOperation operation) { } } - private EndpointClusterAddress fromThriftAddress(ThriftEntityClusterAddress source) { - ThriftEntityAddress address = source.getAddress(); - EndpointObjectHash endpointKey = EndpointObjectHash.fromBytes(address.getEntityId()); - return new EndpointClusterAddress(source.getNodeId(), address.getTenantId(), address.getApplicationToken(), endpointKey); - } - - private void sendMessagesToServer(NeighborConnection server, - Collection messages) { + private void sendMessagesToServer( + NeighborConnection server, + Collection messages) { try { LOG.trace("Sending to server {} messages: {}", server.getId(), messages); server.sendMessages(messages); - } catch (InterruptedException e) { - LOG.error("Error sending events to server: ", e); + } catch (InterruptedException ex) { + LOG.error("Error sending events to server: ", ex); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/DefaultDeltaService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/DefaultDeltaService.java index 967618113f..7754b7f85e 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/DefaultDeltaService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/DefaultDeltaService.java @@ -78,7 +78,8 @@ public class DefaultDeltaService implements DeltaService { private static final Logger LOG = LoggerFactory.getLogger(DefaultDeltaService.class); - private static final Comparator ENDPOINT_GROUP_COMPARATOR = new Comparator() { + private static final Comparator ENDPOINT_GROUP_COMPARATOR = + new Comparator() { @Override public int compare(EndpointGroupDto o1, EndpointGroupDto o2) { @@ -110,13 +111,19 @@ public DefaultDeltaService() { } @Override - public ConfigurationCacheEntry getConfiguration(String appToken, String endpointId, EndpointProfileDto profile) throws GetDeltaException { + public ConfigurationCacheEntry getConfiguration(String appToken, + String endpointId, + EndpointProfileDto profile) + throws GetDeltaException { LOG.debug("[{}][{}] Calculating new configuration", appToken, endpointId); - AppVersionKey appConfigVersionKey = new AppVersionKey(appToken, profile.getConfigurationVersion()); - DeltaCacheKey deltaKey = new DeltaCacheKey(appConfigVersionKey, profile.getGroupState(), EndpointObjectHash.fromBytes(profile + AppVersionKey appConfigVersionKey = new AppVersionKey( + appToken, profile.getConfigurationVersion()); + DeltaCacheKey deltaKey = new DeltaCacheKey( + appConfigVersionKey, profile.getGroupState(), EndpointObjectHash.fromBytes(profile .getUserConfigurationHash()), null, profile.isUseConfigurationRawSchema(), true); LOG.debug("[{}][{}] Built resync delta key {}", appToken, endpointId, deltaKey); - return getDelta(endpointId, profile.getEndpointUserId(), deltaKey, profile.isUseConfigurationRawSchema()); + return getDelta( + endpointId, profile.getEndpointUserId(), deltaKey, profile.isUseConfigurationRawSchema()); } /* @@ -135,7 +142,8 @@ public GetDeltaResponse getDelta(GetDeltaRequest request) throws GetDeltaExcepti if (LOG.isDebugEnabled() && profile != null && profile.getEndpointKeyHash() != null) { endpointId = Base64Util.encode(profile.getEndpointKeyHash()); } - LOG.debug("[{}][{}] Processing configuration request", request.getApplicationToken(), endpointId); + LOG.debug("[{}][{}] Processing configuration request", + request.getApplicationToken(), endpointId); boolean resync = false; if (request.isFirstRequest()) { resync = true; @@ -144,30 +152,19 @@ public GetDeltaResponse getDelta(GetDeltaRequest request) throws GetDeltaExcepti resync = true; } if (resync) { - EndpointConfigurationDto configurationDto = cacheService.getConfByHash(EndpointObjectHash.fromBytes(profile + EndpointConfigurationDto configurationDto = cacheService.getConfByHash( + EndpointObjectHash.fromBytes(profile .getConfigurationHash())); - response = new GetDeltaResponse(GetDeltaResponseType.CONF_RESYNC, new BaseBinaryDelta(configurationDto.getConfiguration())); + response = new GetDeltaResponse(GetDeltaResponseType.CONF_RESYNC, new BaseBinaryDelta( + configurationDto.getConfiguration())); } else { response = new GetDeltaResponse(GetDeltaResponseType.NO_DELTA); } - LOG.debug("[{}][{}] Processed configuration request {}", request.getApplicationToken(), endpointId, response.getResponseType()); + LOG.debug("[{}][{}] Processed configuration request {}", + request.getApplicationToken(), endpointId, response.getResponseType()); return response; } - private void logHashMismatch(GetDeltaRequest request, EndpointProfileDto profile, String endpointId) { - if (profile.getConfigurationHash() != null && LOG.isWarnEnabled()) { - String serverHash = ""; - String clientHash = ""; - if (profile.getConfigurationHash() != null) { - serverHash = MessageEncoderDecoder.bytesToHex(profile.getConfigurationHash()); - } - if (request.getConfigurationHash() != null) { - clientHash = MessageEncoderDecoder.bytesToHex(request.getConfigurationHash().getData()); - } - LOG.warn("[{}] Configuration hash mismatch! server {}, client {}", endpointId, serverHash, clientHash); - } - } - /** * Calculate delta. * @@ -175,7 +172,11 @@ private void logHashMismatch(GetDeltaRequest request, EndpointProfileDto profile * @return the delta cache entry * @throws GetDeltaException the get delta exception */ - private ConfigurationCacheEntry getDelta(final String endpointId, final String userId, DeltaCacheKey deltaKey, boolean useConfigurationRawSchema) throws GetDeltaException { + private ConfigurationCacheEntry getDelta(final String endpointId, + final String userId, + DeltaCacheKey deltaKey, + boolean useConfigurationRawSchema) + throws GetDeltaException { EndpointUserConfigurationDto userConfiguration = findLatestUserConfiguration(userId, deltaKey); final DeltaCacheKey newKey; @@ -192,57 +193,83 @@ private ConfigurationCacheEntry getDelta(final String endpointId, final String u newKey = deltaKey; } - ConfigurationCacheEntry deltaCacheEntry = cacheService.getDelta(newKey, new Computable() { // NOSONAR - @Override - public ConfigurationCacheEntry compute(DeltaCacheKey deltaKey) { - try { - LOG.debug("[{}] Calculating delta for {}", endpointId, deltaKey); - ConfigurationCacheEntry deltaCache; - AbstractKaaData data; - ConfigurationSchemaDto latestConfigurationSchema = cacheService.getConfSchemaByAppAndVersion(deltaKey.getAppConfigVersionKey()); + ConfigurationCacheEntry deltaCacheEntry = cacheService.getDelta( + newKey, new Computable() { // NOSONAR + @Override + public ConfigurationCacheEntry compute(DeltaCacheKey deltaKey) { + try { + LOG.debug("[{}] Calculating delta for {}", endpointId, deltaKey); + AbstractKaaData data; + ConfigurationSchemaDto latestConfigurationSchema = + cacheService.getConfSchemaByAppAndVersion(deltaKey.getAppConfigVersionKey()); - EndpointUserConfigurationDto userConfiguration = findLatestUserConfiguration(userId, deltaKey); + EndpointUserConfigurationDto userConfiguration = findLatestUserConfiguration( + userId, deltaKey); - EndpointObjectHash userConfigurationHash = null; - if (userConfiguration != null) { - userConfigurationHash = EndpointObjectHash.fromString(userConfiguration.getBody()); - } + EndpointObjectHash userConfigurationHash = null; + if (userConfiguration != null) { + userConfigurationHash = EndpointObjectHash.fromString(userConfiguration.getBody()); + } - Pair mergedConfiguration = getMergedConfiguration(endpointId, userConfiguration, deltaKey, latestConfigurationSchema); + Pair mergedConfiguration = getMergedConfiguration( + endpointId, userConfiguration, deltaKey, latestConfigurationSchema); - if (useConfigurationRawSchema) { - data = mergedConfiguration.getV2(); - } else { - data = mergedConfiguration.getV1(); - } + if (useConfigurationRawSchema) { + data = mergedConfiguration.getV2(); + } else { + data = mergedConfiguration.getV1(); + } - LOG.trace("[{}] Merged configuration {}", endpointId, data.getRawData()); - deltaCache = buildBaseResyncDelta(endpointId, data.getRawData(), data.getSchema().getRawSchema(), userConfigurationHash); + LOG.trace("[{}] Merged configuration {}", endpointId, data.getRawData()); + ConfigurationCacheEntry deltaCache = buildBaseResyncDelta( + endpointId, data.getRawData(), + data.getSchema().getRawSchema(), userConfigurationHash); - if (cacheService.getConfByHash(deltaCache.getHash()) == null) { - EndpointConfigurationDto newConfiguration = new EndpointConfigurationDto(); - newConfiguration.setConfiguration(deltaCache.getConfiguration()); - newConfiguration.setConfigurationHash(deltaCache.getHash().getData()); - cacheService.putConfiguration(deltaCache.getHash(), newConfiguration); - } + if (cacheService.getConfByHash(deltaCache.getHash()) == null) { + EndpointConfigurationDto newConfiguration = new EndpointConfigurationDto(); + newConfiguration.setConfiguration(deltaCache.getConfiguration()); + newConfiguration.setConfigurationHash(deltaCache.getHash().getData()); + cacheService.putConfiguration(deltaCache.getHash(), newConfiguration); + } - LOG.debug("[{}] Configuration hash for {} is {}", endpointId, deltaKey, - MessageEncoderDecoder.bytesToHex(deltaCache.getHash().getData())); - return deltaCache; - } catch (GetDeltaException | IOException e) { - throw new RuntimeException(e); // NOSONAR - } - } - }); + LOG.debug("[{}] Configuration hash for {} is {}", endpointId, deltaKey, + MessageEncoderDecoder.bytesToHex(deltaCache.getHash().getData())); + return deltaCache; + } catch (GetDeltaException | IOException ex) { + throw new RuntimeException(ex); // NOSONAR + } + } + }); return deltaCacheEntry; } - private EndpointUserConfigurationDto findLatestUserConfiguration(final String userId, DeltaCacheKey deltaKey) { + private void logHashMismatch(GetDeltaRequest request, + EndpointProfileDto profile, + String endpointId) { + if (profile.getConfigurationHash() != null && LOG.isWarnEnabled()) { + String serverHash = ""; + String clientHash = ""; + if (profile.getConfigurationHash() != null) { + serverHash = MessageEncoderDecoder.bytesToHex(profile.getConfigurationHash()); + } + if (request.getConfigurationHash() != null) { + clientHash = MessageEncoderDecoder.bytesToHex(request.getConfigurationHash().getData()); + } + LOG.warn("[{}] Configuration hash mismatch! server {}, client {}", + endpointId, serverHash, clientHash); + } + } + + private EndpointUserConfigurationDto findLatestUserConfiguration(final String userId, + DeltaCacheKey deltaKey) { EndpointUserConfigurationDto userConfiguration = null; if (userId != null) { - userConfiguration = userConfigurationService.findUserConfigurationByUserIdAndAppTokenAndSchemaVersion(userId, deltaKey - .getAppConfigVersionKey().getApplicationToken(), deltaKey.getAppConfigVersionKey().getVersion()); + userConfiguration = + userConfigurationService.findUserConfigurationByUserIdAndAppTokenAndSchemaVersion( + userId, + deltaKey.getAppConfigVersionKey().getApplicationToken(), + deltaKey.getAppConfigVersionKey().getVersion()); if (userConfiguration != null) { LOG.debug("[{}] User specific configuration found", userId); } else { @@ -252,8 +279,10 @@ private EndpointUserConfigurationDto findLatestUserConfiguration(final String us return userConfiguration; } - private BaseData processEndpointGroups(List endpointGroups, List configurations, - ConfigurationSchemaDto configurationSchema) throws OverrideException, IOException { + private BaseData processEndpointGroups(List endpointGroups, + List configurations, + ConfigurationSchemaDto configurationSchema) + throws OverrideException, IOException { // create sorted map to store configurations sorted by endpoint group // weight // put all endpoint groups as keys into the map @@ -277,21 +306,26 @@ private BaseData processEndpointGroups(List endpointGroups, Li } } if (!endpointGroupFound) { - LOG.debug("No Configuration found for Endpoint Group; Endpoint Group Id: {}", endpointGroup.getId()); + LOG.debug("No Configuration found for Endpoint Group; Endpoint Group Id: {}", + endpointGroup.getId()); } } - OverrideAlgorithm configurationMerger = configurationOverrideFactory.createConfigurationOverrideAlgorithm(); + OverrideAlgorithm configurationMerger = + configurationOverrideFactory.createConfigurationOverrideAlgorithm(); return configurationMerger.override(baseConfig, overrideConfigs); } /** - * Gets the latest conf from cache + * Gets the latest conf from cache. * * @return the latest conf from cache */ - private Pair getMergedConfiguration(final String endpointId, final EndpointUserConfigurationDto userConfiguration, - final DeltaCacheKey cacheKey, ConfigurationSchemaDto latestConfigurationSchema) throws GetDeltaException { + private Pair getMergedConfiguration( + final String endpointId, + final EndpointUserConfigurationDto userConfiguration, + final DeltaCacheKey cacheKey, + ConfigurationSchemaDto latestConfigurationSchema) throws GetDeltaException { final List egsList = cacheKey.getEndpointGroups(); // return Pair in order to cache both calculated configuration and optimize performance @@ -316,28 +350,33 @@ public Pair compute(List key) { ConfigurationDto configuration = null; if (!StringUtils.isBlank(egs.getConfigurationId())) { - configuration = configurationService.findConfigurationById(egs.getConfigurationId()); + configuration = configurationService.findConfigurationById( + egs.getConfigurationId()); if (configuration != null) { configurations.add(configuration); } } if (configurationSchema == null && configuration != null) { - configurationSchema = configurationService.findConfSchemaById(configuration.getSchemaId()); + configurationSchema = configurationService.findConfSchemaById( + configuration.getSchemaId()); } } - BaseData baseData = processEndpointGroups(endpointGroups, configurations, configurationSchema); + BaseData baseData = processEndpointGroups( + endpointGroups, configurations, configurationSchema); // converting merged base schema to raw schema - String ctlSchema = cacheService.getFlatCtlSchemaById(latestConfigurationSchema.getCtlSchemaId()); + String ctlSchema = cacheService.getFlatCtlSchemaById( + latestConfigurationSchema.getCtlSchemaId()); JsonNode json = new ObjectMapper().readTree(baseData.getRawData()); AvroUtils.removeUuids(json); RawData rawData = new RawData(new RawSchema(ctlSchema), json.toString()); return new Pair<>(baseData, rawData); - } catch (OverrideException | IOException oe) { - LOG.error("[{}] Unexpected exception occurred while merging configuration: ", endpointId, oe); - throw new RuntimeException(oe); // NOSONAR + } catch (OverrideException | IOException ex) { + LOG.error("[{}] Unexpected exception occurred while merging configuration: ", + endpointId, ex); + throw new RuntimeException(ex); // NOSONAR } finally { LOG.trace("[{}] getMergedGroupConfiguration.compute end", endpointId); } @@ -345,21 +384,27 @@ public Pair compute(List key) { }); if (userConfiguration != null) { - OverrideAlgorithm configurationMerger = configurationOverrideFactory.createConfigurationOverrideAlgorithm(); - OverrideSchema overrideSchema = new OverrideSchema(latestConfigurationSchema.getOverrideSchema()); + OverrideAlgorithm configurationMerger = + configurationOverrideFactory.createConfigurationOverrideAlgorithm(); + OverrideSchema overrideSchema = new OverrideSchema( + latestConfigurationSchema.getOverrideSchema()); try { - LOG.trace("Merging group configuration with user configuration: {}", userConfiguration.getBody()); + LOG.trace("Merging group configuration with user configuration: {}", + userConfiguration.getBody()); BaseData baseData = configurationMerger.override(mergedConfiguration.getV1(), - Collections.singletonList(new OverrideData(overrideSchema, userConfiguration.getBody()))); + Collections.singletonList(new OverrideData( + overrideSchema, userConfiguration.getBody()))); JsonNode json = new ObjectMapper().readTree(baseData.getRawData()); AvroUtils.removeUuids(json); - RawData rawData = new RawData(new RawSchema(mergedConfiguration.getV2().getSchema().getRawSchema()), json.toString()); + RawData rawData = new RawData(new RawSchema( + mergedConfiguration.getV2().getSchema().getRawSchema()), json.toString()); mergedConfiguration = new Pair<>(baseData, rawData); - } catch (OverrideException | IOException oe) { - LOG.error("[{}] Unexpected exception occurred while merging configuration: ", endpointId, oe); - throw new GetDeltaException(oe); + } catch (OverrideException | IOException ex) { + LOG.error("[{}] Unexpected exception occurred while merging configuration: ", + endpointId, ex); + throw new GetDeltaException(ex); } finally { LOG.trace("[{}] getMergedConfiguration.compute end", endpointId); } @@ -367,9 +412,15 @@ public Pair compute(List key) { return mergedConfiguration; } - private ConfigurationCacheEntry buildBaseResyncDelta(String endpointId, String jsonData, String schema, EndpointObjectHash userConfigurationHash) throws IOException { + private ConfigurationCacheEntry buildBaseResyncDelta(String endpointId, + String jsonData, + String schema, + EndpointObjectHash userConfigurationHash) + throws IOException { byte[] configuration = GenericAvroConverter.toRawData(jsonData, schema); - return new ConfigurationCacheEntry(configuration, new BaseBinaryDelta(configuration), EndpointObjectHash.fromSha1(configuration), + return new ConfigurationCacheEntry( + configuration, new BaseBinaryDelta(configuration), + EndpointObjectHash.fromSha1(configuration), userConfigurationHash); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/DeltaService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/DeltaService.java index 43541fa975..032cba63b6 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/DeltaService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/DeltaService.java @@ -39,7 +39,7 @@ public interface DeltaService { GetDeltaResponse getDelta(GetDeltaRequest request) throws GetDeltaException; /** - * Gets the up to date configuration for given endpoint profile + * Gets the up to date configuration for given endpoint profile. * * @param appToken - the application token * @param endpointKey - the endpoint key @@ -47,6 +47,8 @@ public interface DeltaService { * @return cache entry * @throws GetDeltaException the get delta exception */ - ConfigurationCacheEntry getConfiguration(String appToken, String endpointKey, EndpointProfileDto profile) throws GetDeltaException; + ConfigurationCacheEntry getConfiguration( + String appToken, String endpointKey, + EndpointProfileDto profile) throws GetDeltaException; } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/HistoryDelta.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/HistoryDelta.java index 190ae65a4c..7f3e555cc7 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/HistoryDelta.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/delta/HistoryDelta.java @@ -56,7 +56,9 @@ public class HistoryDelta { * @param topicListChanged the topic list changed * @param seqNumberChanged the sequence number changed flag */ - public HistoryDelta(List endpointGroupStates, boolean configurationChanged, boolean topicListChanged, boolean seqNumberChanged) { + public HistoryDelta(List endpointGroupStates, + boolean configurationChanged, + boolean topicListChanged, boolean seqNumberChanged) { super(); this.endpointGroupStates = endpointGroupStates; this.configurationChanged = configurationChanged; 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 9c02e6d698..4567e80f7b 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 @@ -79,21 +79,26 @@ public class DefaultEventService implements EventService { */ private static final Logger LOG = LoggerFactory.getLogger(DefaultEventService.class); - private static final AtomicLong eventSequence = new AtomicLong(UUID.randomUUID().getLeastSignificantBits()); //NOSONAR + private static final AtomicLong eventSequence = new AtomicLong( + UUID.randomUUID().getLeastSignificantBits()); //NOSONAR /** - * AVRO event converter + * AVRO event converter. */ - private final ThreadLocal> eventConverter = new ThreadLocal>() { - @Override - protected AvroByteArrayConverter initialValue() { - return new AvroByteArrayConverter( - org.kaaproject.kaa.common.endpoint.gen.Event.class); - } - }; + private final ThreadLocal> + eventConverter = + new ThreadLocal>() { + @Override + protected AvroByteArrayConverter + initialValue() { + return new AvroByteArrayConverter<>( + org.kaaproject.kaa.common.endpoint.gen.Event.class); + } + }; + @Autowired private OperationsServerConfig operationsServerConfig; /** - * ID is thriftHost:thriftPort + * ID is thriftHost:thriftPort. */ private volatile String id; private volatile Neighbors neighbors; @@ -112,7 +117,7 @@ public DefaultEventService() { } /** - * Map RouteOperation into EventRouteUpdateType + * Map RouteOperation into EventRouteUpdateType. * * @param operation RouteOperation * @return EventRouteUpdateType @@ -132,7 +137,7 @@ private static EventRouteUpdateType transformUpdateType(RouteOperation operation } /** - * Map EventRouteUpdateType into RouteOperation + * Map EventRouteUpdateType into RouteOperation. * * @param updateType EventRouteUpdateType * @return RouteOperation @@ -155,12 +160,15 @@ private static RouteOperation transformUpdateType(EventRouteUpdateType updateTyp * @param ecfVersions List * @return thrift List */ - private static List transformECFV( - List ecfVersions) { - List ecfvThL = new ArrayList<>(); + private + static List + transformEcfv(List ecfVersions) { + List ecfvThL = + new ArrayList<>(); if (ecfVersions != null) { for (EventClassFamilyVersion ecfv : ecfVersions) { - org.kaaproject.kaa.server.common.thrift.gen.operations.EventClassFamilyVersion ecfvTh = new org.kaaproject.kaa.server.common.thrift.gen.operations.EventClassFamilyVersion(); + org.kaaproject.kaa.server.common.thrift.gen.operations.EventClassFamilyVersion ecfvTh = + new org.kaaproject.kaa.server.common.thrift.gen.operations.EventClassFamilyVersion(); ecfvTh.setEndpointClassFamilyId(ecfv.getEcfId()); ecfvTh.setEndpointClassFamilyVersion(ecfv.getVersion()); ecfvThL.add(ecfvTh); @@ -173,7 +181,7 @@ private static List()); - neighbors = new Neighbors(KaaThriftService.OPERATIONS_SERVICE, new MessageTemplate(this), + neighbors = new Neighbors<>(KaaThriftService.OPERATIONS_SERVICE, new MessageTemplate(this), operationsServerConfig.getMaxNumberNeighborConnections()); } @@ -202,22 +210,32 @@ public void sendEvent(RemoteEndpointEvent remoteEndpointEvent) { notifyListenersOnServerProblem(serverId); return; } - RouteAddress routeAddress = new RouteAddress(ByteBuffer.wrap(remoteEndpointEvent.getRecipient().getEndpointKey().getData()), + RouteAddress routeAddress = new RouteAddress( + ByteBuffer.wrap(remoteEndpointEvent.getRecipient().getEndpointKey().getData()), remoteEndpointEvent.getRecipient().getApplicationToken(), serverId); ByteBuffer eventData; try { org.kaaproject.kaa.server.sync.Event eventSource = remoteEndpointEvent.getEvent().getEvent(); - eventData = ByteBuffer.wrap(eventConverter.get().toByteArray(AvroEncDec.convert(eventSource))); - org.kaaproject.kaa.server.common.thrift.gen.operations.EndpointEvent endpointEvent = new org.kaaproject.kaa.server.common.thrift.gen.operations.EndpointEvent( - remoteEndpointEvent.getEvent().getId().toString(), - ByteBuffer.wrap(remoteEndpointEvent.getEvent().getSender().getData()), eventData, remoteEndpointEvent.getEvent() - .getCreateTime(), remoteEndpointEvent.getEvent().getVersion()); - Event event = new Event(remoteEndpointEvent.getUserId(), remoteEndpointEvent.getTenantId(), endpointEvent, routeAddress); + eventData = ByteBuffer.wrap( + eventConverter.get().toByteArray(AvroEncDec.convert(eventSource))); + org.kaaproject.kaa.server.common.thrift.gen.operations.EndpointEvent endpointEvent = + new org.kaaproject.kaa.server.common.thrift.gen.operations.EndpointEvent( + remoteEndpointEvent.getEvent().getId().toString(), + ByteBuffer.wrap( + remoteEndpointEvent.getEvent().getSender().getData()), + eventData, + remoteEndpointEvent.getEvent() + .getCreateTime(), remoteEndpointEvent.getEvent().getVersion()); + Event event = new Event( + remoteEndpointEvent.getUserId(), + remoteEndpointEvent.getTenantId(), + endpointEvent, + routeAddress); server.sendMessages(packMessage(event)); - } catch (IOException e1) { - LOG.error("Error on converting Event to byte array: skiping this event message", e1); - } catch (InterruptedException e) { - LOG.error("Error sending events to server: ", e); + } catch (IOException ex) { + LOG.error("Error on converting Event to byte array: skiping this event message", ex); + } catch (InterruptedException ex) { + LOG.error("Error sending events to server: ", ex); notifyListenersOnServerProblem(serverId); } } @@ -265,7 +283,8 @@ public void sendRouteInfo(Collection routeInfos, String... serverIdLi * (org.kaaproject.kaa.server.operations.service.event.UserRouteInfo) */ @Override - public void sendUserRouteInfo(org.kaaproject.kaa.server.operations.service.event.UserRouteInfo routeInfo) { + public void sendUserRouteInfo( + org.kaaproject.kaa.server.operations.service.event.UserRouteInfo routeInfo) { LOG.debug("EventService: sendUserRouteInfo()....."); List> servers = neighbors.getNeighbors(); @@ -350,7 +369,8 @@ public void sendEventMessage(List messages) { @Override public void sendEndpointRouteInfo(GlobalRouteInfo routeInfo) { LOG.trace("calculating server for user {}", routeInfo.getUserId()); - String serverId = Neighbors.getServerId(resolver.getNode(routeInfo.getUserId()).getConnectionInfo()); + String serverId = Neighbors.getServerId( + resolver.getNode(routeInfo.getUserId()).getConnectionInfo()); sendMessagesToServer(packMessage(routeInfo), serverId); } @@ -388,8 +408,13 @@ public String getUserNode(String userId) { @Override public void setZkNode(OperationsNode operationsNode) { this.operationsNode = operationsNode; - this.id = Neighbors.getServerId(KaaThriftService.OPERATIONS_SERVICE, this.operationsNode.getNodeInfo().getConnectionInfo()); - neighbors.setZkNode(KaaThriftService.OPERATIONS_SERVICE, this.operationsNode.getNodeInfo().getConnectionInfo(), operationsNode); + this.id = Neighbors.getServerId( + KaaThriftService.OPERATIONS_SERVICE, + this.operationsNode.getNodeInfo().getConnectionInfo()); + neighbors.setZkNode( + KaaThriftService.OPERATIONS_SERVICE, + this.operationsNode.getNodeInfo().getConnectionInfo(), + operationsNode); if (resolver != null) { updateResolver(this.resolver); } @@ -425,7 +450,8 @@ private List packMessage(List routes) { * @return List */ private List packMessage(UserRouteInfo userRoute) { - return Collections.singletonList(new Message(EventMessageType.USER_ROUTE_INFO, getEventId(), null, null, userRoute, null, null)); + return Collections.singletonList(new Message( + EventMessageType.USER_ROUTE_INFO, getEventId(), null, null, userRoute, null, null)); } /** @@ -435,7 +461,8 @@ private List packMessage(UserRouteInfo userRoute) { * @return List */ private List packMessage(Event event) { - return Collections.singletonList(new Message(EventMessageType.EVENT, getEventId(), event, null, null, null, null)); + return Collections.singletonList(new Message( + EventMessageType.EVENT, getEventId(), event, null, null, null, null)); } /** @@ -455,17 +482,21 @@ protected void notifyListenersOnServerProblem(String id) { * @param routeInfos Collection * @return List */ - private List transformEventRouteFromRouteInfoCollection(Collection routeInfos) { + private List transformEventRouteFromRouteInfoCollection( + Collection routeInfos) { List routes = new ArrayList<>(); - HashMap> routeInfosTh = new HashMap<>(); // NOSONAR + HashMap> + routeInfosTh = new HashMap<>(); // NOSONAR for (RouteInfo ri : routeInfos) { - org.kaaproject.kaa.server.common.thrift.gen.operations.RouteInfo riTh = new org.kaaproject.kaa.server.common.thrift.gen.operations.RouteInfo( - transformUpdateType(ri.getRouteOperation()), transformECFV(ri.getEcfVersions()), ri.getAddress().getApplicationToken(), - ByteBuffer.wrap(ri.getAddress().getEndpointKey().getData())); + org.kaaproject.kaa.server.common.thrift.gen.operations.RouteInfo riTh = + new org.kaaproject.kaa.server.common.thrift.gen.operations.RouteInfo( + transformUpdateType(ri.getRouteOperation()), transformEcfv(ri.getEcfVersions()), + ri.getAddress().getApplicationToken(), + ByteBuffer.wrap(ri.getAddress().getEndpointKey().getData())); UserTenantKey key = new UserTenantKey(ri.getUserId(), ri.getTenantId()); if (!routeInfosTh.containsKey(key)) { - routeInfosTh.put(key, new ArrayList()); + routeInfosTh.put(key, new ArrayList<>()); } routeInfosTh.get(key).add(riTh); } @@ -495,12 +526,13 @@ private void sendMessagesToServer(List messages, String serverId) { sendMessagesToServer(server, messages); } - private void sendMessagesToServer(NeighborConnection server, List messages) { + private void sendMessagesToServer(NeighborConnection server, + List messages) { try { LOG.trace("Sending to server {} messages: {}", server.getId(), messages); server.sendMessages(messages); - } catch (InterruptedException e) { - LOG.error("Error sending events to server: ", e); + } catch (InterruptedException ex) { + LOG.error("Error sending events to server: ", ex); notifyListenersOnServerProblem(server.getId()); } } @@ -528,22 +560,27 @@ private void onEndpointStateUpdate(EndpointStateUpdate update) { * @param route EventRoute */ private void onRouteUpdate(EventRoute route) { - LOG.debug("onEventRouteUpdate .... {} routes updated in {} listeners", route.getRouteInfo().size(), listeners.size()); + LOG.debug("onEventRouteUpdate .... {} routes updated in {} listeners", + route.getRouteInfo().size(), listeners.size()); for (EventServiceListener listener : listeners) { - for (org.kaaproject.kaa.server.common.thrift.gen.operations.RouteInfo routeInfo : route.getRouteInfo()) { + for (org.kaaproject.kaa.server.common.thrift.gen.operations.RouteInfo routeInfo + : route.getRouteInfo()) { String applicationToken = routeInfo.getApplicationToken(); EndpointObjectHash endpointKey = EndpointObjectHash.fromBytes(routeInfo.getEndpointId()); - RouteTableAddress address = new RouteTableAddress(endpointKey, applicationToken, route.getOperationsServerId()); + RouteTableAddress address = new RouteTableAddress( + endpointKey, applicationToken, route.getOperationsServerId()); List ecfVersions = new ArrayList<>(); - for (org.kaaproject.kaa.server.common.thrift.gen.operations.EventClassFamilyVersion ecfv : routeInfo - .getEventClassFamilyVersion()) { - EventClassFamilyVersion ecf = new EventClassFamilyVersion(ecfv.getEndpointClassFamilyId(), + for (org.kaaproject.kaa.server.common.thrift.gen.operations.EventClassFamilyVersion ecfv + : routeInfo.getEventClassFamilyVersion()) { + EventClassFamilyVersion ecf = new EventClassFamilyVersion( + ecfv.getEndpointClassFamilyId(), ecfv.getEndpointClassFamilyVersion()); ecfVersions.add(ecf); } - listener.onRouteInfo(new RouteInfo(route.getTenantId(), route.getUserId(), address, ecfVersions)); + listener.onRouteInfo(new RouteInfo( + route.getTenantId(), route.getUserId(), address, ecfVersions)); } } } @@ -555,13 +592,16 @@ private void onRouteUpdate(EventRoute route) { * @param userRoute UserRouteInfo object */ private void onUserRouteInfo(UserRouteInfo userRoute) { - LOG.debug("eventUserRouteInfo .... User routes updates in {} listeners", listeners.size()); - LOG.debug("UserRouteInfo UserId={}; TenantId={}; OperationServerId={}", userRoute.getUserId(), userRoute.getTenantId(), + LOG.debug("eventUserRouteInfo .... User routes updates in {} listeners", + listeners.size()); + LOG.debug("UserRouteInfo UserId={}; TenantId={}; OperationServerId={}", + userRoute.getUserId(), userRoute.getTenantId(), userRoute.getOperationsServerId()); for (EventServiceListener listener : listeners) { - org.kaaproject.kaa.server.operations.service.event.UserRouteInfo routeInfo = new org.kaaproject.kaa.server.operations.service.event.UserRouteInfo( - userRoute.getTenantId(), userRoute.getUserId(), userRoute.getOperationsServerId(), - transformUpdateType(userRoute.getUpdateType())); + org.kaaproject.kaa.server.operations.service.event.UserRouteInfo routeInfo = + new org.kaaproject.kaa.server.operations.service.event.UserRouteInfo( + userRoute.getTenantId(), userRoute.getUserId(), userRoute.getOperationsServerId(), + transformUpdateType(userRoute.getUpdateType())); listener.onUserRouteInfo(routeInfo); } } @@ -578,16 +618,22 @@ private void onEvent(Event event) { for (EventServiceListener listener : listeners) { org.kaaproject.kaa.server.sync.Event localEvent; try { - localEvent = AvroEncDec.convert(eventConverter.get().fromByteArray(event.getEndpointEvent().getEventData())); - EndpointEvent endpointEvent = new EndpointEvent(EndpointObjectHash.fromBytes(event.getEndpointEvent().getSender()), - localEvent, UUID.fromString(event.getEndpointEvent().getUuid()), event.getEndpointEvent().getCreateTime(), event - .getEndpointEvent().getVersion()); - RouteTableAddress recipient = new RouteTableAddress(EndpointObjectHash.fromBytes(event.getRouteAddress().getEndpointKey()), - event.getRouteAddress().getApplicationToken(), event.getRouteAddress().getOperationsServerId()); - RemoteEndpointEvent remoteEvent = new RemoteEndpointEvent(event.getTenantId(), event.getUserId(), endpointEvent, recipient); + localEvent = AvroEncDec.convert(eventConverter.get().fromByteArray( + event.getEndpointEvent().getEventData())); + EndpointEvent endpointEvent = new EndpointEvent( + EndpointObjectHash.fromBytes(event.getEndpointEvent().getSender()), + localEvent, UUID.fromString( + event.getEndpointEvent().getUuid()), event.getEndpointEvent().getCreateTime(), + event.getEndpointEvent().getVersion()); + RouteTableAddress recipient = new RouteTableAddress( + EndpointObjectHash.fromBytes(event.getRouteAddress().getEndpointKey()), + event.getRouteAddress().getApplicationToken(), + event.getRouteAddress().getOperationsServerId()); + RemoteEndpointEvent remoteEvent = new RemoteEndpointEvent( + event.getTenantId(), event.getUserId(), endpointEvent, recipient); listener.onEvent(remoteEvent); - } catch (IOException e) { - LOG.error("Error on converting byte array to Event: skiping this event message", e); + } catch (IOException ex) { + LOG.error("Error on converting byte array to Event: skiping this event message", ex); } } @@ -620,8 +666,8 @@ public void onNodeAdded(OperationsNodeInfo node) { } private List packMessage(GlobalRouteInfo routeInfo) { - EventMessageType type = EventMessageType.ENDPOINT_ROUTE_UPDATE; - List messages = new LinkedList<>(); + final EventMessageType type = EventMessageType.ENDPOINT_ROUTE_UPDATE; + final List messages = new LinkedList<>(); EndpointRouteUpdate route = new EndpointRouteUpdate(); route.setTenantId(routeInfo.getTenantId()); @@ -635,7 +681,8 @@ private List packMessage(GlobalRouteInfo routeInfo) { opsServerId = id; } - RouteAddress routeAddress = new RouteAddress(ByteBuffer.wrap(routeInfo.getAddress().getEndpointKey().getData()), routeInfo + RouteAddress routeAddress = new RouteAddress( + ByteBuffer.wrap(routeInfo.getAddress().getEndpointKey().getData()), routeInfo .getAddress().getApplicationToken(), opsServerId); route.setRouteAddress(routeAddress); @@ -645,8 +692,8 @@ private List packMessage(GlobalRouteInfo routeInfo) { } private List packMessage(EndpointUserConfigurationUpdate update) { - EventMessageType type = EventMessageType.ENDPOINT_STATE_UPDATE; - List messages = new LinkedList<>(); + final EventMessageType type = EventMessageType.ENDPOINT_STATE_UPDATE; + final List messages = new LinkedList<>(); EndpointStateUpdate msg = new EndpointStateUpdate(); msg.setTenantId(update.getTenantId()); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventClassFamilyVersion.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventClassFamilyVersion.java index f3e974b884..ac63a8eb90 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventClassFamilyVersion.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/EventClassFamilyVersion.java @@ -19,9 +19,7 @@ import java.io.Serializable; public final class EventClassFamilyVersion implements Serializable { - /** - * - */ + private static final long serialVersionUID = 7302504644662229284L; 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 d2244ca5af..d4631ab0fa 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 @@ -68,7 +68,7 @@ public interface EventService { void sendRouteInfo(Collection routeInfos, String... serverIdList); /** - * Send UserRouteInfo to all neighbors, + * Send UserRouteInfo to all neighbors. * * @param routeInfo UserRouteInfo */ diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTableKey.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTableKey.java index de3d14c23d..bd32964e61 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTableKey.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/RouteTableKey.java @@ -21,9 +21,6 @@ public final class RouteTableKey implements Serializable { - /** - * - */ private static final long serialVersionUID = 3363397161525196106L; diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/UserRouteInfo.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/UserRouteInfo.java index 2899d2207d..60f9620c6b 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/UserRouteInfo.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/UserRouteInfo.java @@ -30,7 +30,10 @@ public UserRouteInfo(String tenantId, String userId) { this(tenantId, userId, null, RouteOperation.ADD); } - public UserRouteInfo(String tenantId, String userId, String serverId, RouteOperation routeOperation) { + public UserRouteInfo(String tenantId, + String userId, + String serverId, + RouteOperation routeOperation) { super(); this.tenantId = tenantId; this.userId = userId; diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/UserTenantKey.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/UserTenantKey.java index 47eee5e27e..c43495befe 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/UserTenantKey.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/event/UserTenantKey.java @@ -24,6 +24,8 @@ public final class UserTenantKey { private final String tenantId; /** + * All-args constructor. + * * @param userId the user id * @param tenantId the user id */ @@ -33,6 +35,8 @@ public UserTenantKey(String userId, String tenantId) { } /** + * Returns a user identifier. + * * @return the userId */ public String getUserId() { @@ -40,6 +44,8 @@ public String getUserId() { } /** + * Returns a tenant identifier. + * * @return the tenantId */ public String getTenantId() { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/DefaultFilterEvaluator.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/DefaultFilterEvaluator.java index 414aad9fad..04aa38e4e2 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/DefaultFilterEvaluator.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/DefaultFilterEvaluator.java @@ -57,7 +57,9 @@ public DefaultFilterEvaluator() { } @Override - public void init(EndpointProfileDto profile, String profileSchemaBody, String serverProfileSchemaBody) { + public void init(EndpointProfileDto profile, + String profileSchemaBody, + String serverProfileSchemaBody) { GenericAvroConverter endpointProfileConverter = new GenericAvroConverter<>( new Schema.Parser().parse(profileSchemaBody)); GenericAvroConverter serverProfileConverter = new GenericAvroConverter<>( @@ -65,10 +67,12 @@ public void init(EndpointProfileDto profile, String profileSchemaBody, String se this.epKey = Base64Util.encode(profile.getEndpointKeyHash()); try { if (profile.getServerProfileBody() != null) { - serverProfileGenericRecord = serverProfileConverter.decodeJson(profile.getServerProfileBody()); + serverProfileGenericRecord = serverProfileConverter.decodeJson( + profile.getServerProfileBody()); } if (profile.getClientProfileBody() != null) { - clientProfileGenericRecord = endpointProfileConverter.decodeJson(profile.getClientProfileBody()); + clientProfileGenericRecord = endpointProfileConverter.decodeJson( + profile.getClientProfileBody()); } } catch (IOException ioe) { LOG.error("Error decoding avro object from Json string", ioe); @@ -84,7 +88,7 @@ public void init(EndpointProfileDto profile, String profileSchemaBody, String se */ @Override public boolean matches(ProfileFilterDto filter) { - Expression expression = new SpelExpressionParser().parseExpression(filter.getBody()); + final Expression expression = new SpelExpressionParser().parseExpression(filter.getBody()); StandardEvaluationContext evaluationContext; if (filter.getEndpointProfileSchemaVersion() != null) { evaluationContext = new StandardEvaluationContext(clientProfileGenericRecord); diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/DefaultFilterService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/DefaultFilterService.java index 4f0233935e..7fc72f86c5 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/DefaultFilterService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/DefaultFilterService.java @@ -67,7 +67,8 @@ public DefaultFilterService() { * java.lang.String) */ @Override - public List getAllMatchingFilters(AppProfileVersionsKey key, EndpointProfileDto profile) { + public List getAllMatchingFilters(AppProfileVersionsKey key, + EndpointProfileDto profile) { String endpointProfileSchemaBody = getEndpointProfileSchemaBody(key); String serverProfileSchemaBody = getServerProfileSchemaBody(key); @@ -97,7 +98,8 @@ public List getAllMatchingFilters(AppProfileVersionsKey key, E */ @Override public boolean matches(String appToken, String profileFilterId, EndpointProfileDto profile) { - AppProfileVersionsKey key = new AppProfileVersionsKey(appToken, profile.getClientProfileVersion(), + AppProfileVersionsKey key = new AppProfileVersionsKey( + appToken, profile.getClientProfileVersion(), profile.getServerProfileVersion()); String endpointProfileSchemaBody = getEndpointProfileSchemaBody(key); String serverProfileSchemaBody = getServerProfileSchemaBody(key); @@ -116,27 +118,35 @@ private boolean checkFilter(FilterEvaluator filterEvaluator, ProfileFilterDto fi LOG.trace("profile body matched"); return true; } - } catch (EvaluationException ee) { - LOG.warn("Failed to process filter [{}]: {} due to evaluate exception. Please check your filter body", filter.getId(), - filter.getBody(), ee); - } catch (Exception e) { - LOG.error("Failed to process filter [{}]: {} due to exception", filter.getId(), filter.getBody(), e); + } catch (EvaluationException ex) { + LOG.warn("Failed to process filter [{}]: {} due to evaluate exception. " + + "Please check your filter body", + filter.getId(), + filter.getBody(), + ex); + } catch (Exception ex) { + LOG.error("Failed to process filter [{}]: {} due to exception", + filter.getId(), filter.getBody(), ex); } return false; } private String getServerProfileSchemaBody(AppProfileVersionsKey key) { - ServerProfileSchemaDto serverProfileSchema = cacheService.getServerProfileSchemaByAppAndVersion(new AppVersionKey(key - .getApplicationToken(), key.getServerProfileSchemaVersion())); + ServerProfileSchemaDto serverProfileSchema = + cacheService.getServerProfileSchemaByAppAndVersion(new AppVersionKey(key + .getApplicationToken(), key.getServerProfileSchemaVersion())); - String serverProfileSchemaBody = cacheService.getFlatCtlSchemaById(serverProfileSchema.getCtlSchemaId()); + String serverProfileSchemaBody = cacheService.getFlatCtlSchemaById( + serverProfileSchema.getCtlSchemaId()); return serverProfileSchemaBody; } private String getEndpointProfileSchemaBody(AppProfileVersionsKey key) { - EndpointProfileSchemaDto endpointProfileSchema = cacheService.getProfileSchemaByAppAndVersion(new AppVersionKey(key - .getApplicationToken(), key.getEndpointProfileSchemaVersion())); - String endpointProfileSchemaBody = cacheService.getFlatCtlSchemaById(endpointProfileSchema.getCtlSchemaId()); + EndpointProfileSchemaDto endpointProfileSchema = + cacheService.getProfileSchemaByAppAndVersion(new AppVersionKey( + key.getApplicationToken(), key.getEndpointProfileSchemaVersion())); + String endpointProfileSchemaBody = cacheService.getFlatCtlSchemaById( + endpointProfileSchema.getCtlSchemaId()); return endpointProfileSchemaBody; } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/FilterEvaluator.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/FilterEvaluator.java index f69474ebff..ba55fce988 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/FilterEvaluator.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/FilterEvaluator.java @@ -27,13 +27,15 @@ public interface FilterEvaluator { /** - * Initialize Filter evaluator with profile information + * Initialize Filter evaluator with profile information. * * @param profile - endpoint profile * @param endpointProfileSchemaBody - endpoint profile schema body * @param serverProfileSchemaBody - server profile schema body */ - void init(EndpointProfileDto profile, String endpointProfileSchemaBody, String serverProfileSchemaBody); + void init(EndpointProfileDto profile, + String endpointProfileSchemaBody, + String serverProfileSchemaBody); /** * Evaluates profile filter. diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/FilterService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/FilterService.java index da5a4c07cd..7de31d33c4 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/FilterService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/FilterService.java @@ -39,7 +39,8 @@ public interface FilterService { * @param profile the profile * @return the all matching filters */ - List getAllMatchingFilters(AppProfileVersionsKey appProfileVersionsKey, EndpointProfileDto profile); + List getAllMatchingFilters(AppProfileVersionsKey appProfileVersionsKey, + EndpointProfileDto profile); /** * Check if profileBody matches filter that is represented by filter id. diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/el/GenericRecordPropertyAccessor.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/el/GenericRecordPropertyAccessor.java index 5a617a469d..c1ddf3c9b5 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/el/GenericRecordPropertyAccessor.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/filter/el/GenericRecordPropertyAccessor.java @@ -37,7 +37,8 @@ public Class[] getSpecificTargetClasses() { } /* (non-Javadoc) - * @see org.springframework.expression.PropertyAccessor#canRead(org.springframework.expression.EvaluationContext, java.lang.Object, java.lang.String) + * @see org.springframework.expression.PropertyAccessor#canRead(org.springframework + * .expression.EvaluationContext, java.lang.Object, java.lang.String) */ @Override public boolean canRead(EvaluationContext context, Object target, String name) @@ -47,7 +48,8 @@ public boolean canRead(EvaluationContext context, Object target, String name) } /* (non-Javadoc) - * @see org.springframework.expression.PropertyAccessor#read(org.springframework.expression.EvaluationContext, java.lang.Object, java.lang.String) + * @see org.springframework.expression.PropertyAccessor#read(org.springframework + * .expression.EvaluationContext, java.lang.Object, java.lang.String) */ @Override public TypedValue read(EvaluationContext context, Object target, String name) @@ -57,7 +59,8 @@ public TypedValue read(EvaluationContext context, Object target, String name) } /* (non-Javadoc) - * @see org.springframework.expression.PropertyAccessor#canWrite(org.springframework.expression.EvaluationContext, java.lang.Object, java.lang.String) + * @see org.springframework.expression.PropertyAccessor#canWrite(org.springframework + * .expression.EvaluationContext, java.lang.Object, java.lang.String) */ @Override public boolean canWrite(EvaluationContext context, Object target, @@ -66,7 +69,8 @@ public boolean canWrite(EvaluationContext context, Object target, } /* (non-Javadoc) - * @see org.springframework.expression.PropertyAccessor#write(org.springframework.expression.EvaluationContext, java.lang.Object, java.lang.String, java.lang.Object) + * @see org.springframework.expression.PropertyAccessor#write(org.springframework + * .expression.EvaluationContext, java.lang.Object, java.lang.String, java.lang.Object) */ @Override public void write(EvaluationContext context, Object target, String name, 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 2b920be640..66b72f1333 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 @@ -74,10 +74,14 @@ public class DefaultHistoryDeltaService implements HistoryDeltaService { * java.lang.String, int) */ @Override - public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken, int curAppSeqNumber) { + public HistoryDelta getDelta(EndpointProfileDto profile, + String applicationToken, + int curAppSeqNumber) { String endpointId = Base64Util.encode(profile); - ConfigurationIdKey confIdKey = new ConfigurationIdKey(applicationToken, curAppSeqNumber, profile.getConfigurationVersion()); - AppProfileVersionsKey appVersionsKey = new AppProfileVersionsKey(applicationToken, profile.getClientProfileVersion(), + ConfigurationIdKey confIdKey = new ConfigurationIdKey( + applicationToken, curAppSeqNumber, profile.getConfigurationVersion()); + AppProfileVersionsKey appVersionsKey = new AppProfileVersionsKey( + applicationToken, profile.getClientProfileVersion(), profile.getServerProfileVersion()); List filters = filterService.getAllMatchingFilters(appVersionsKey, profile); LOG.debug("[{}] Found {} matching filters", endpointId, filters.size()); @@ -87,11 +91,13 @@ public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken EndpointGroupStateDto groupAllState = new EndpointGroupStateDto(); groupAllState.setEndpointGroupId(groupDto.getId()); - groupAllState.setConfigurationId(cacheService.getConfIdByKey(confIdKey.copyWithNewEGId(groupDto.getId()))); + groupAllState.setConfigurationId(cacheService.getConfIdByKey( + confIdKey.copyWithNewEGId(groupDto.getId()))); result.add(groupAllState); for (ProfileFilterDto filter : filters) { - String confId = cacheService.getConfIdByKey(confIdKey.copyWithNewEGId(filter.getEndpointGroupId())); + String confId = cacheService.getConfIdByKey( + confIdKey.copyWithNewEGId(filter.getEndpointGroupId())); EndpointGroupStateDto endpointGroupState = new EndpointGroupStateDto(); endpointGroupState.setEndpointGroupId(filter.getEndpointGroupId()); endpointGroupState.setProfileFilterId(filter.getId()); @@ -110,7 +116,10 @@ public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken * java.lang.String, int, int) */ @Override - public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken, int oldAppSeqNumber, int curAppSeqNumber) { + public HistoryDelta getDelta(EndpointProfileDto profile, + String applicationToken, + int oldAppSeqNumber, + int curAppSeqNumber) { String endpointId = Base64Util.encode(profile.getEndpointKeyHash()); HistoryDelta historyDelta = new HistoryDelta(); @@ -119,20 +128,23 @@ public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken if (profile.getGroupState() != null && profile.getGroupState().size() > 0) { historyDelta.setEndpointGroupStates(profile.getGroupState()); } else { - historyDelta.setEndpointGroupStates(new ArrayList()); + historyDelta.setEndpointGroupStates(new ArrayList<>()); } return historyDelta; } else { historyDelta.setSeqNumberChanged(true); } - HistoryKey historyKey = new HistoryKey(applicationToken, oldAppSeqNumber, curAppSeqNumber, profile.getConfigurationVersion(), + HistoryKey historyKey = new HistoryKey( + applicationToken, oldAppSeqNumber, curAppSeqNumber, profile.getConfigurationVersion(), profile.getClientProfileVersion(), profile.getServerProfileVersion()); - ConfigurationIdKey confIdKey = new ConfigurationIdKey(applicationToken, curAppSeqNumber, profile.getConfigurationVersion()); + ConfigurationIdKey confIdKey = new ConfigurationIdKey( + applicationToken, curAppSeqNumber, profile.getConfigurationVersion()); List endpointGroups; - LOG.debug("[{}] Fetching changes from history. From seq number: {} to {}", endpointId, historyKey.getOldSeqNumber(), + LOG.debug("[{}] Fetching changes from history. From seq number: {} to {}", + endpointId, historyKey.getOldSeqNumber(), historyKey.getNewSeqNumber()); Map groupsMap = getOldGroupMap(profile); @@ -156,13 +168,13 @@ public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken if (egs != null) { if (changeType == ChangeType.REMOVE_TOPIC || changeType == ChangeType.ADD_TOPIC) { - LOG.trace("[{}] Detected {} for {} on group {} which means topic list change", endpointId, changeType, - change.getTopicId(), change.getEndpointGroupId()); + LOG.trace("[{}] Detected {} for {} on group {} which means topic list change", + endpointId, changeType, change.getTopicId(), change.getEndpointGroupId()); historyDelta.setTopicListChanged(true); continue; } else if (changeType == ChangeType.REMOVE_CONF || changeType == ChangeType.ADD_CONF) { - LOG.trace("[{}] Detected {} for {} on group {} which means configuration change", endpointId, changeType, - change.getConfigurationId(), change.getEndpointGroupId()); + LOG.trace("[{}] Detected {} for {} on group {} which means configuration change", + endpointId, changeType, change.getConfigurationId(), change.getEndpointGroupId()); if (changeType == ChangeType.ADD_CONF) { egs.setConfigurationId(change.getConfigurationId()); } else { @@ -170,15 +182,20 @@ public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken } historyDelta.setConfigurationChanged(true); } else if (changeType == ChangeType.REMOVE_PROF) { - LOG.trace("[{}] Detected {} for {} on group {} which means configuration/topic list change", endpointId, changeType, + LOG.trace("[{}] Detected {} for {} on group {} which means " + + "configuration/topic list change", + endpointId, changeType, change.getProfileFilterId(), change.getEndpointGroupId()); groupsMap.remove(egs.getEndpointGroupId()); historyDelta.setAllChanged(); } else if (changeType == ChangeType.ADD_PROF) { - LOG.trace("[{}] Detected {} for {} on group {}", endpointId, changeType, change.getProfileFilterId(), + LOG.trace("[{}] Detected {} for {} on group {}", + endpointId, changeType, change.getProfileFilterId(), change.getEndpointGroupId()); - if (!filterService.matches(historyKey.getAppToken(), change.getProfileFilterId(), profile)) { - LOG.trace("[{}] Detected {} does not match current profile body which means configuration/topic list change", + if (!filterService.matches( + historyKey.getAppToken(), change.getProfileFilterId(), profile)) { + LOG.trace("[{}] Detected {} does not match current profile body " + + "which means configuration/topic list change", endpointId, change.getProfileFilterId()); groupsMap.remove(egs.getEndpointGroupId()); historyDelta.setAllChanged(); @@ -188,10 +205,13 @@ public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken } } else { if (changeType == ChangeType.ADD_PROF) { - LOG.trace("[{}] Detected {} for {} on group {}", endpointId, changeType, change.getProfileFilterId(), + LOG.trace("[{}] Detected {} for {} on group {}", + endpointId, changeType, change.getProfileFilterId(), change.getEndpointGroupId()); - if (filterService.matches(historyKey.getAppToken(), change.getProfileFilterId(), profile)) { - LOG.trace("[{}] Detected {} match current profile body which means possible configuration/topic list change", + if (filterService.matches( + historyKey.getAppToken(), change.getProfileFilterId(), profile)) { + LOG.trace("[{}] Detected {} match current profile body which means " + + "possible configuration/topic list change", endpointId, change.getProfileFilterId()); egs = new EndpointGroupStateDto(groupId, change.getProfileFilterId(), null); groupsMap.put(groupId, egs); @@ -210,7 +230,9 @@ public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken if (confId != null) { entry.getValue().setConfigurationId(confId); } else { - LOG.debug("[{}] Attempt failed. This is possibly group with topic list but without configuration", endpointId, + LOG.debug("[{}] Attempt failed. This is possibly group with topic " + + "list but without configuration", + endpointId, entry.getKey()); } } @@ -229,6 +251,7 @@ public HistoryDelta getDelta(EndpointProfileDto profile, String applicationToken * @return the old group map */ private Map getOldGroupMap(EndpointProfileDto profile) { - return profile.getGroupState().stream().collect(Collectors.toMap(EndpointGroupStateDto::getEndpointGroupId, Function.identity())); + return profile.getGroupState().stream().collect( + Collectors.toMap(EndpointGroupStateDto::getEndpointGroupId, Function.identity())); } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/loadbalance/DefaultLoadBalancingService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/loadbalance/DefaultLoadBalancingService.java index 3c52ef00c5..8ad9f82f9d 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/loadbalance/DefaultLoadBalancingService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/loadbalance/DefaultLoadBalancingService.java @@ -83,8 +83,8 @@ public void stop() { pool.shutdown(); try { pool.awaitTermination(3, TimeUnit.SECONDS); - } catch (InterruptedException e) { - LOG.error("Failed to terminate service", e); + } catch (InterruptedException ex) { + LOG.error("Failed to terminate service", ex); } } @@ -92,12 +92,13 @@ public void stop() { public void onStatusUpdate(AkkaServiceStatus status) { try { OperationsNodeInfo nodeInfo = operationsNode.getNodeInfo(); - OperatingSystemMXBean operatingSystemMXBean = ManagementFactory.getOperatingSystemMXBean(); - nodeInfo.setLoadInfo(new LoadInfo(status.getEndpointCount(), operatingSystemMXBean.getSystemLoadAverage())); + OperatingSystemMXBean operatingSystemMxBean = ManagementFactory.getOperatingSystemMXBean(); + nodeInfo.setLoadInfo(new LoadInfo( + status.getEndpointCount(), operatingSystemMxBean.getSystemLoadAverage())); operationsNode.updateNodeData(nodeInfo); LOG.info("Updated load info: {}", nodeInfo.getLoadInfo()); - } catch (Exception e) { - LOG.error("Failed to report status update to control service", e); + } catch (Exception ex) { + LOG.error("Failed to report status update to control service", ex); } } } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/DefaultLogAppenderBuilder.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/DefaultLogAppenderBuilder.java index 8e2b49725c..4d223f9938 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/DefaultLogAppenderBuilder.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/DefaultLogAppenderBuilder.java @@ -32,7 +32,8 @@ public DefaultLogAppenderBuilder() { } @Override - public LogAppender getAppender(LogAppenderDto appenderConfig) throws ReflectiveOperationException { + public LogAppender getAppender(LogAppenderDto appenderConfig) + throws ReflectiveOperationException { if (appenderConfig == null) { throw new IllegalArgumentException("appender config can't be null"); } @@ -41,18 +42,20 @@ public LogAppender getAppender(LogAppenderDto appenderConfig) throws ReflectiveO Class appenderClass = (Class) Class .forName(appenderConfig.getPluginClassName()); LogAppender logAppender = appenderClass.newInstance(); - LOG.debug("Init log appender [{}] with appender configuration [{}].", logAppender, appenderConfig); + LOG.debug("Init log appender [{}] with appender configuration [{}].", + logAppender, appenderConfig); logAppender.setName(appenderConfig.getName()); logAppender.setAppenderId(appenderConfig.getId()); logAppender.setApplicationToken(appenderConfig.getApplicationToken()); logAppender.init(appenderConfig); return logAppender; - } catch (ClassNotFoundException e) { + } catch (ClassNotFoundException ex) { LOG.error("Unable to find custom appender class {}", appenderConfig.getPluginClassName()); - throw e; - } catch (InstantiationException | IllegalAccessException e) { - LOG.error("Unable to instantiate custom appender from class {}", appenderConfig.getPluginClassName()); - throw e; + throw ex; + } catch (InstantiationException | IllegalAccessException ex) { + LOG.error("Unable to instantiate custom appender from class {}", + appenderConfig.getPluginClassName()); + throw ex; } } } \ No newline at end of file diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/DefaultLogAppenderService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/DefaultLogAppenderService.java index 2b925dfbf0..3f4a1c1e94 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/DefaultLogAppenderService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/DefaultLogAppenderService.java @@ -63,8 +63,8 @@ public List getApplicationAppenders(String applicationId) { try { LogAppender logAppender = logAppenderResolver.getAppender(appender); logAppenders.add(logAppender); - } catch (Exception e) { - LOG.warn("Can't initialize log appender [{}]", appender, e); + } catch (Exception ex) { + LOG.warn("Can't initialize log appender [{}]", appender, ex); continue; } } @@ -74,8 +74,10 @@ public List getApplicationAppenders(String applicationId) { @Override public List getApplicationAppendersByLogSchemaVersion( String applicationId, int schemaVersion) { - LOG.debug("Get log appenders by application id [{}] and schema version [{}]", applicationId, schemaVersion); - List appenders = logAppendersService.findLogAppendersByAppIdAndSchemaVersion(applicationId, schemaVersion); + LOG.debug("Get log appenders by application id [{}] and schema version [{}]", + applicationId, schemaVersion); + List appenders = logAppendersService.findLogAppendersByAppIdAndSchemaVersion( + applicationId, schemaVersion); LOG.debug("Found all appenders [{}] for application and schema version.", appenders); List logAppenders = new ArrayList<>(appenders.size()); @@ -83,8 +85,8 @@ public List getApplicationAppendersByLogSchemaVersion( try { LogAppender logAppender = logAppenderResolver.getAppender(appender); logAppenders.add(logAppender); - } catch (Exception e) { - LOG.warn("Can't initialize log appender [{}], exception catched: {}", appender, e); + } catch (Exception ex) { + LOG.warn("Can't initialize log appender [{}], exception catched: {}", appender, ex); continue; } } @@ -99,17 +101,19 @@ public LogAppender getApplicationAppender(String appenderId) { LogAppender logAppender = null; try { logAppender = logAppenderResolver.getAppender(appender); - } catch (Exception e) { - LOG.warn("Can't initialize log appender [{}]", appender, e); + } catch (Exception ex) { + LOG.warn("Can't initialize log appender [{}]", appender, ex); } return logAppender; } @Override public LogSchema getLogSchema(String applicationId, int logSchemaVersion) { - LOG.debug("Fetching log schema for application {} and version {}", applicationId, logSchemaVersion); + LOG.debug("Fetching log schema for application {} and version {}", + applicationId, logSchemaVersion); LogSchema logSchema = null; - LogSchemaDto logSchemaDto = logSchemaService.findLogSchemaByAppIdAndVersion(applicationId, logSchemaVersion); + LogSchemaDto logSchemaDto = logSchemaService.findLogSchemaByAppIdAndVersion( + applicationId, logSchemaVersion); CTLSchemaDto ctlSchema = ctlService.findCTLSchemaById(logSchemaDto.getCtlSchemaId()); String logFlatSchema = ctlService.flatExportAsString(ctlSchema); if (logSchemaDto != null) { diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/LogAppenderBuilder.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/LogAppenderBuilder.java index bcdad81f1c..121811c2b1 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/LogAppenderBuilder.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/LogAppenderBuilder.java @@ -22,6 +22,8 @@ public interface LogAppenderBuilder { /** + * Returns a log appender. + * * @param appenderConfig the appender config * @return the log appender * @throws ReflectiveOperationException the reflective operation exception diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/LogAppenderService.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/LogAppenderService.java index a30dea18b5..4a3f5cb63d 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/LogAppenderService.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/logs/LogAppenderService.java @@ -41,7 +41,8 @@ public interface LogAppenderService { * @param schemaVersion the log schema version * @return List of all Appenders available for Application and log schema version */ - List getApplicationAppendersByLogSchemaVersion(String applicationId, int schemaVersion); + List getApplicationAppendersByLogSchemaVersion(String applicationId, + int schemaVersion); /** * Gets the log schema. diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/thrift/OperationsThriftServiceImpl.java b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/thrift/OperationsThriftServiceImpl.java index 04cf2072c7..4bb34a196a 100644 --- a/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/thrift/OperationsThriftServiceImpl.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/operations/service/thrift/OperationsThriftServiceImpl.java @@ -92,7 +92,7 @@ public class OperationsThriftServiceImpl implements OperationsThriftService.Ifac ApplicationService applicationService; /** - * The event service + * The event service. */ @Autowired EventService eventService; @@ -127,7 +127,8 @@ public void onNotification(Notification notification) throws TException { */ @Override public void setRedirectionRule(RedirectionRule redirectionRule) throws TException { - LOG.debug("Received setRedirectionRule from control Dynamic Load Mgmt service {}", redirectionRule); + LOG.debug("Received setRedirectionRule from control Dynamic Load Mgmt service {}", + redirectionRule); LOG.debug("Notify akka service.."); akkaService.onRedirectionRule(redirectionRule); } @@ -144,11 +145,11 @@ public void sendMessages(List messages) throws TException { } @Override - public void sendUserConfigurationUpdates(List updates) throws TException { + public void sendUserConfigurationUpdates(List updates) + throws TException { for (UserConfigurationUpdate update : updates) { - akkaService - .onUserConfigurationUpdate(org.kaaproject.kaa.server.operations.service.akka.messages.core.user.UserConfigurationUpdate - .fromThrift(update)); + akkaService.onUserConfigurationUpdate(org.kaaproject.kaa.server.operations.service + .akka.messages.core.user.UserConfigurationUpdate.fromThrift(update)); } } @@ -169,18 +170,24 @@ private void processCacheNotification(Notification notification) { if (notification.getProfileFilterId() != null) { ProfileFilterDto filterDto = cacheService.getFilter(notification.getProfileFilterId()); LOG.debug("Processing filter {}", filterDto); - if (filterDto.getEndpointProfileSchemaId() != null && filterDto.getServerProfileSchemaId() != null) { - cacheService.resetFilters(new AppProfileVersionsKey(appDto.getApplicationToken(), filterDto + if (filterDto.getEndpointProfileSchemaId() != null + && filterDto.getServerProfileSchemaId() != null) { + cacheService.resetFilters(new AppProfileVersionsKey( + appDto.getApplicationToken(), filterDto .getEndpointProfileSchemaVersion(), filterDto.getServerProfileSchemaVersion())); } else if (filterDto.getServerProfileSchemaVersion() == null) { - for (VersionDto version : profileService.findProfileSchemaVersionsByAppId(appDto.getId())) { + for (VersionDto version + : profileService.findProfileSchemaVersionsByAppId(appDto.getId())) { LOG.debug("Processing version {}", version); - cacheService.resetFilters(new AppProfileVersionsKey(appDto.getApplicationToken(), version.getVersion(), null)); + cacheService.resetFilters(new AppProfileVersionsKey( + appDto.getApplicationToken(), version.getVersion(), null)); } } else { - for (ServerProfileSchemaDto version : serverProfileService.findServerProfileSchemasByAppId(appDto.getId())) { + for (ServerProfileSchemaDto version + : serverProfileService.findServerProfileSchemasByAppId(appDto.getId())) { LOG.debug("Processing version {}", version); - cacheService.resetFilters(new AppProfileVersionsKey(appDto.getApplicationToken(), null, version.getVersion())); + cacheService.resetFilters(new AppProfileVersionsKey( + appDto.getApplicationToken(), null, version.getVersion())); } } } @@ -188,17 +195,23 @@ private void processCacheNotification(Notification notification) { cacheService.resetGroup(notification.getGroupId()); } if (notification.getAppSeqNumber() != 0) { - LOG.debug("Going to update application {} with seqNumber {} in thread {}", appDto.getApplicationToken(), + LOG.debug("Going to update application {} with seqNumber {} in thread {}", + appDto.getApplicationToken(), notification.getAppSeqNumber(), Thread.currentThread().getId()); synchronized (cacheService) { - int currentSeqNumber = cacheService.getAppSeqNumber(appDto.getApplicationToken()).getSeqNumber(); + int currentSeqNumber = cacheService.getAppSeqNumber( + appDto.getApplicationToken()).getSeqNumber(); if (currentSeqNumber < notification.getAppSeqNumber()) { - cacheService.putAppSeqNumber(appDto.getApplicationToken(), new AppSeqNumber(appDto.getTenantId(), appDto.getId(), - appDto.getApplicationToken(), notification.getAppSeqNumber())); - LOG.debug("Update application {} with seqNumber {} in thread {}", appDto.getApplicationToken(), + cacheService.putAppSeqNumber( + appDto.getApplicationToken(), + new AppSeqNumber(appDto.getTenantId(), appDto.getId(), + appDto.getApplicationToken(), notification.getAppSeqNumber())); + LOG.debug("Update application {} with seqNumber {} in thread {}", + appDto.getApplicationToken(), notification.getAppSeqNumber(), Thread.currentThread().getId()); } else { - LOG.debug("Update ignored. application {} already has seqNumber {}", appDto.getApplicationToken(), + LOG.debug("Update ignored. application {} already has seqNumber {}", + appDto.getApplicationToken(), notification.getAppSeqNumber()); } @@ -225,7 +238,8 @@ public void onServerProfileUpdate(ThriftServerProfileUpdateMessage message) thro } @Override - public void onEndpointDeregistration(ThriftEndpointDeregistrationMessage message) throws TException { + public void onEndpointDeregistration(ThriftEndpointDeregistrationMessage message) + throws TException { LOG.debug("Received Event about endpoint deregistration {}", message); byte[] address = message.getAddress().getEntityId(); EndpointObjectHash hash = EndpointObjectHash.fromBytes(address); 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 index 2d64ab5a11..026d77b330 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 @@ -44,7 +44,7 @@ public AbstractCTLMigration(Connection connection) { public void beforeTransform() throws SQLException { // delete relation between _schems to schems - dd.dropUnnamedFK(getPrefixTableName() + "_schems", "schems"); + dd.dropUnnamedFk(getPrefixTableName() + "_schems", "schems"); } diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CTLAggregation.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlAggregation.java similarity index 65% rename from server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CTLAggregation.java rename to server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlAggregation.java index 9cc2c1e023..9720a733f3 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CTLAggregation.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlAggregation.java @@ -47,20 +47,20 @@ import java.util.Set; //TODO simplify logic of aggregation and add promotion -public class CTLAggregation { - private static final Logger LOG = LoggerFactory.getLogger(CTLAggregation.class); +public class CtlAggregation { + private static final Logger LOG = LoggerFactory.getLogger(CtlAggregation.class); private Connection connection; private QueryRunner runner; private DataDefinition dd; - private Map> schemasToCTL; + private Map> schemasToCtl; private Set ctls; - public CTLAggregation(Connection connection) { + public CtlAggregation(Connection connection) { this.connection = connection; runner = new QueryRunner(); dd = new DataDefinition(connection); - schemasToCTL = new HashMap<>(); + schemasToCtl = new HashMap<>(); ctls = new HashSet<>(); } @@ -68,41 +68,59 @@ public CTLAggregation(Connection connection) { /* * Return schemas and CTLs map that further used for creating new records in base_schema table * */ - public Map> aggregate(List schemas) throws SQLException, ConfigurationGenerationException, IOException { - Long currentCTLMetaId = runner.query(connection, "select max(id) as max_id from ctl_metainfo", rs -> rs.next() ? rs.getLong("max_id") : null); - Long currentCtlId = runner.query(connection, "select max(id) as max_id from ctl", rs -> rs.next() ? rs.getLong("max_id") : null); + public Map> aggregate(List schemas) + throws SQLException, ConfigurationGenerationException, IOException { + Long currentCtlMetaId = runner.query(connection, + "select max(id) as max_id from ctl_metainfo", + rs -> rs.next() ? rs.getLong("max_id") : null); - List flatCtls = runner.query(connection, "select c.id as ctlId, body, m.id as metaInfoId, fqn, application_id as appId, tenant_id as tenantId from ctl c join ctl_metainfo m on c.metainfo_id = m.id", new BeanListHandler<>(FlatCtl.class)); + Long currentCtlId = runner.query(connection, + "select max(id) as max_id from ctl", + rs -> rs.next() ? rs.getLong("max_id") : null); + + List flatCtls = runner.query(connection, + "select c.id as ctlId, body, m.id as metaInfoId, fqn, application_id as appId, " + + "tenant_id as tenantId from ctl c join ctl_metainfo m on c.metainfo_id = m.id", + new BeanListHandler<>(FlatCtl.class)); // fetch existed CTLs for (FlatCtl flatCtl : flatCtls) { Ctl ctl = flatCtl.toCtl(); ctl.setExistInDb(true); ctls.add(ctl); - schemasToCTL.put(ctl, new ArrayList<>()); + schemasToCtl.put(ctl, new ArrayList<>()); } // CTL creation for (Schema schema : schemas) { - currentCTLMetaId++; + currentCtlMetaId++; currentCtlId++; - org.apache.avro.Schema schemaBody = new org.apache.avro.Schema.Parser().parse(schema.getSchems()); + org.apache.avro.Schema schemaBody = new org.apache.avro.Schema.Parser() + .parse(schema.getSchems()); String fqn = schemaBody.getFullName(); RawSchema rawSchema = new RawSchema(schemaBody.toString()); - DefaultRecordGenerationAlgorithm algotithm = new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory()); - String defaultRecord = algotithm.getRootData().getRawData(); + DefaultRecordGenerationAlgorithm algorithm = + new DefaultRecordGenerationAlgorithmImpl<>(rawSchema, new RawDataFactory()); + String defaultRecord = algorithm.getRootData().getRawData(); Long tenantId = null; if (schema.getAppId() != null) { - tenantId = runner.query(connection, "select tenant_id from application where id = " + schema.getAppId(), rs -> rs.next() ? rs.getLong("tenant_id") : null); + tenantId = runner.query( + connection, + "select tenant_id from application where id = " + schema.getAppId(), + rs -> rs.next() ? rs.getLong("tenant_id") : null); } else { - tenantId = runner.query(connection, "select tenant_id from events_class where id = " + schema.getId(), rs -> rs.next() ? rs.getLong("tenant_id") : null); + tenantId = runner.query( + connection, + "select tenant_id from events_class where id = " + schema.getId(), + rs -> rs.next() ? rs.getLong("tenant_id") : null); } - Ctl ctl = new Ctl(currentCtlId, new CtlMetaInfo(currentCTLMetaId, fqn, schema.getAppId(), tenantId), defaultRecord); + Ctl ctl = new Ctl(currentCtlId, new CtlMetaInfo( + currentCtlMetaId, fqn, schema.getAppId(), tenantId), defaultRecord); // aggregation if (ctls.isEmpty()) { - schemasToCTL.put(ctl, new ArrayList<>(asList(schema))); + schemasToCtl.put(ctl, new ArrayList<>(asList(schema))); ctls.add(ctl); } else { Ctl ctlToCompare = sameFqn(ctls, ctl); @@ -130,9 +148,12 @@ public Map> aggregate(List schemas) throws SQLExceptio } else { ctlToCompare = sameBody(ctls, ctl); if (ctlToCompare != null) { - LOG.warn("Schemas {} and {} have different fqn but same body {}", ctl.getMetaInfo().getFqn(), ctlToCompare.getMetaInfo().getFqn(), ctl.getDefaultRecord()); + LOG.warn("Schemas {} and {} have different fqn but same body {}", + ctl.getMetaInfo().getFqn(), + ctlToCompare.getMetaInfo().getFqn(), + ctl.getDefaultRecord()); } - schemasToCTL.put(ctl, new ArrayList<>(asList(schema))); + schemasToCtl.put(ctl, new ArrayList<>(asList(schema))); ctls.add(ctl); } } @@ -147,14 +168,16 @@ public Map> aggregate(List schemas) throws SQLExceptio } CtlMetaInfo mi = ctl.getMetaInfo(); - Schema s = schemasToCTL.get(ctl).get(0); - runner.insert(connection, "insert into ctl_metainfo values(?, ?, ?, ?)", new ScalarHandler(), mi.getId(), mi.getFqn(), mi.getAppId(), mi.getTenantId()); - runner.insert(connection, "insert into ctl values(?, ?, ?, ?, ?, ?, ?)", new ScalarHandler(), ctl.getId(), s.getSchems(), s.getCreatedTime(), - s.getCreatedUsername(), ctl.getDefaultRecord(), s.getVersion(), mi.getId()); + Schema schema = schemasToCtl.get(ctl).get(0); + runner.insert(connection, "insert into ctl_metainfo values(?, ?, ?, ?)", + new ScalarHandler(), mi.getId(), mi.getFqn(), mi.getAppId(), mi.getTenantId()); + runner.insert(connection, "insert into ctl values(?, ?, ?, ?, ?, ?, ?)", + new ScalarHandler(), ctl.getId(), schema.getSchems(), schema.getCreatedTime(), + schema.getCreatedUsername(), ctl.getDefaultRecord(), schema.getVersion(), mi.getId()); } - return schemasToCTL; + return schemasToCtl; } @@ -177,15 +200,15 @@ private Ctl sameBody(Set set, Ctl ctl) { return null; } + private boolean sameBody(Ctl c1, Ctl c2) { + return c1.getDefaultRecord().equals(c2.getDefaultRecord()); + } + private boolean bothAppIdNull(Ctl c1, Ctl c2) { return c1.getMetaInfo().getAppId() == null && c2.getMetaInfo().getAppId() == null; } - private boolean sameBody(Ctl c1, Ctl c2) { - return c1.getDefaultRecord().equals(c2.getDefaultRecord()); - } - private boolean sameAppId(Ctl c1, Ctl c2) { return c1.getMetaInfo().getAppId().equals(c2.getMetaInfo().getAppId()); } @@ -198,7 +221,9 @@ private boolean sameTenant(Ctl c1, Ctl c2) { private void putToMapSchema(Ctl c1, Ctl newCtl, Schema schema, String scope) { if (!sameBody(c1, newCtl)) { - LOG.warn("Schemas in different {}s' scopes have different bodies {} and {} but the same fqn {}", scope, newCtl.getDefaultRecord(), c1.getDefaultRecord(), newCtl.getMetaInfo().getFqn()); + LOG.warn( + "Schemas in different {}s' scopes have different bodies {} and {} but the same fqn {}", + scope, newCtl.getDefaultRecord(), c1.getDefaultRecord(), newCtl.getMetaInfo().getFqn()); } else { LOG.debug("Schemas with fqn {} in {}s {} and {} can be promoted to {} scope", newCtl.getMetaInfo().getFqn(), scope, @@ -208,18 +233,21 @@ private void putToMapSchema(Ctl c1, Ctl newCtl, Schema schema, String scope) { ); } - schemasToCTL.put(newCtl, new ArrayList<>(asList(schema))); + schemasToCtl.put(newCtl, new ArrayList<>(asList(schema))); ctls.add(newCtl); } private void aggregateSchemas(Ctl c1, Ctl c2, Schema schema) { if (!sameBody(c1, c2)) { CtlMetaInfo mi = c1.getMetaInfo(); - String message = format("Unable to do migrate due to schemas with same fqn[%s] and scope[appId=%d, tenant=%d] but different bodies", mi.getFqn(), mi.getAppId(), mi.getTenantId()); + String message = format( + "Unable to do migrate due to schemas with same fqn[%s] and " + + "scope[appId=%d, tenant=%d] but different bodies", + mi.getFqn(), mi.getAppId(), mi.getTenantId()); throw new MigrationException(message); } LOG.debug("Schemas with fqn {} were aggregated.", c1.getMetaInfo().getFqn()); - List sc = schemasToCTL.get(c1); + List sc = schemasToCtl.get(c1); sc.add(schema); } } 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 similarity index 89% rename from server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CTLConfigurationMigration.java rename to server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlConfigurationMigration.java index 708747d510..cf4b027357 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,10 +22,10 @@ import java.sql.Connection; import java.sql.SQLException; -public class CTLConfigurationMigration extends AbstractCTLMigration { +public class CtlConfigurationMigration extends AbstractCTLMigration { - public CTLConfigurationMigration(Connection connection) { + public CtlConfigurationMigration(Connection connection) { super(connection); } @@ -34,7 +34,7 @@ public void beforeTransform() throws SQLException { super.beforeTransform(); // change FK constraint between table that contains data and appropriate _schems table - dd.dropUnnamedFK("configuration", "configuration_schems"); + dd.dropUnnamedFk("configuration", "configuration_schems"); dd.alterTable(getPrefixTableName()) .add(constraint("FK_configuration_schems_id") .foreignKey("configuration_schems_id") 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 similarity index 68% rename from server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CTLEventsMigration.java rename to server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlEventsMigration.java index 2627cce7c1..aef419ce36 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,15 +34,16 @@ 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 = "events_class_family_versions"; + private static final String EVENT_CLASS_FAMILY_VERSION_TABLE_NAME = + "events_class_family_versions"; private static final String EVENT_CLASS_TABLE_NAME = "events_class"; private static final String BASE_SCHEMA_TABLE_NAME = "base_schems"; private static final String APPLICATION_EVENT_MAP_TABLE_NAME = "application_event_map"; - public CTLEventsMigration(Connection connection) { + public CtlEventsMigration(Connection connection) { super(connection); } @@ -54,9 +55,12 @@ protected String getPrefixTableName() { @Override public void beforeTransform() throws SQLException { - dd.dropUnnamedFK(EVENT_CLASS_TABLE_NAME, EVENT_CLASS_FAMILY_TABLE_NAME); - dd.dropUnnamedFK(APPLICATION_EVENT_MAP_TABLE_NAME, EVENT_CLASS_TABLE_NAME); - runner.update(connection, "ALTER TABLE " + BASE_SCHEMA_TABLE_NAME + " CHANGE application_id application_id bigint(20)"); + dd.dropUnnamedFk(EVENT_CLASS_TABLE_NAME, EVENT_CLASS_FAMILY_TABLE_NAME); + dd.dropUnnamedFk(APPLICATION_EVENT_MAP_TABLE_NAME, EVENT_CLASS_TABLE_NAME); + runner.update( + connection, "ALTER TABLE " + + BASE_SCHEMA_TABLE_NAME + + " CHANGE application_id application_id bigint(20)"); } @Override @@ -83,24 +87,35 @@ protected List transform() throws SQLException { // fetch schemas of appropriate feature like configuration List schemas = new ArrayList<>(); - List oldESVs = runner.query(connection, - "SELECT id, schems, created_time, created_username FROM " + EVENT_SCHEMA_VERSION_TABLE_NAME, + final List oldEsvs = runner.query(connection, + "SELECT id, schems, created_time, created_username FROM " + + EVENT_SCHEMA_VERSION_TABLE_NAME, new BeanListHandler(EventSchemaVersion.class)); - List oldECs = runner.query(connection, "SELECT id, schems, version FROM " + EVENT_CLASS_TABLE_NAME + - " WHERE schems not like '{\"type\":\"enum\"%'", new BeanListHandler(EventClass.class)); + List oldECs = runner.query( + connection, "SELECT id, schems, version FROM " + EVENT_CLASS_TABLE_NAME + + " WHERE schems not like '{\"type\":\"enum\"%'", + new BeanListHandler<>(EventClass.class)); + + runner.update( + connection, "ALTER TABLE " + EVENT_SCHEMA_VERSION_TABLE_NAME + " DROP COLUMN schems"); + + runner.update( + connection, "ALTER TABLE " + EVENT_SCHEMA_VERSION_TABLE_NAME + " RENAME " + + EVENT_CLASS_FAMILY_VERSION_TABLE_NAME); + + runner.update( + connection, "ALTER TABLE " + EVENT_CLASS_TABLE_NAME + + " CHANGE events_class_family_id events_class_family_versions_id bigint(20)"); - runner.update(connection, "ALTER TABLE " + EVENT_SCHEMA_VERSION_TABLE_NAME + " DROP COLUMN schems"); - runner.update(connection, "ALTER TABLE " + EVENT_SCHEMA_VERSION_TABLE_NAME + " RENAME " + EVENT_CLASS_FAMILY_VERSION_TABLE_NAME); - runner.update(connection, "ALTER TABLE " + EVENT_CLASS_TABLE_NAME + " CHANGE events_class_family_id events_class_family_versions_id bigint(20)"); runner.update(connection, "ALTER TABLE " + EVENT_CLASS_TABLE_NAME + " DROP COLUMN schems"); runner.update(connection, "ALTER TABLE " + EVENT_CLASS_TABLE_NAME + " DROP COLUMN version"); for (EventClass ec : oldECs) { - updateFamilyVersionId(ec, oldESVs, runner); + updateFamilyVersionId(ec, oldEsvs, runner); } for (EventClass ec : oldECs) { - EventSchemaVersion esv = findParent(ec, oldESVs); + EventSchemaVersion esv = findParent(ec, oldEsvs); Long id = ec.getId(); Long createdTime = esv.getCreatedTime(); @@ -112,33 +127,48 @@ protected List transform() throws SQLException { Long applicationId = null; String type = null; //fixme: what is type? - Schema schema = new Schema(id, version, name, description, createUsername, createdTime, applicationId, schems, type); + Schema schema = new Schema( + id, version, name, description, createUsername, + createdTime, applicationId, schems, type); schemas.add(schema); } // 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 " + EVENT_CLASS_TABLE_NAME, rs -> rs.next() ? rs.getLong("max_id") : null); + Long shift = runner.query( + connection, "select max(id) as max_id from " + EVENT_CLASS_TABLE_NAME, + rs -> rs.next() ? rs.getLong("max_id") : null); Long idShift = BaseSchemaIdCounter.getInstance().getAndShift(shift); - runner.update(connection, "update " + EVENT_CLASS_TABLE_NAME + " set id = id + " + idShift + " order by id desc"); - runner.update(connection, "update " + APPLICATION_EVENT_MAP_TABLE_NAME + " set events_class_id = events_class_id + " + idShift + " order by id desc"); - schemas.forEach(s -> s.setId(s.getId() + idShift)); + runner.update( + connection, + "update " + EVENT_CLASS_TABLE_NAME + " set id = id + " + idShift + " order by id desc"); + runner.update( + connection, + "update " + APPLICATION_EVENT_MAP_TABLE_NAME + " set events_class_id = events_class_id + " + + idShift + " order by id desc"); + + schemas.forEach(s -> s.setId(s.getId() + idShift)); return schemas; } private EventSchemaVersion findParent(EventClass ec, List versions) { for (EventSchemaVersion esv : versions) { - if (ecBelongToThisFamilyVersion(ec, esv)) return esv; + if (ecBelongToThisFamilyVersion(ec, esv)) { + return esv; + } } return null; } - private void updateFamilyVersionId(EventClass ec, List versions, QueryRunner runner) throws SQLException { + private void updateFamilyVersionId(EventClass ec, + List versions, + QueryRunner runner) throws SQLException { for (EventSchemaVersion esv : versions) { if (ecBelongToThisFamilyVersion(ec, esv)) { int updateCount = runner.update(this.connection, - "UPDATE " + EVENT_CLASS_TABLE_NAME + " SET events_class_family_versions_id=? WHERE id=?", + "UPDATE " + EVENT_CLASS_TABLE_NAME + + " SET events_class_family_versions_id=? WHERE id=?", esv.getId(), ec.getId()); if (updateCount != 1) { System.err.println("Error: failed to update event class's reference to ECFV: " + ec); @@ -156,7 +186,7 @@ private boolean ecBelongToThisFamilyVersion(EventClass ec, EventSchemaVersion es String name = jsonNode.get("name").asText(); return esv.getSchems().contains(name) && esv.getSchems().contains(namespace); - } catch (IOException e) { + } catch (IOException ex) { System.err.println("Failed to read EventClass schema: " + ec); } return false; @@ -166,7 +196,7 @@ private String parseName(String body) { try { JsonNode jsonNode = new ObjectMapper().readTree(body); return jsonNode.get("name").asText(); - } catch (IOException e) { + } catch (IOException ex) { System.err.println("Failed to parse name from schema: " + body); } return ""; 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 similarity index 88% rename from server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CTLLogMigration.java rename to server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlLogMigration.java index da5fdd2b4e..6e1f8fe16f 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,11 +18,11 @@ import java.sql.Connection; -public class CTLLogMigration extends AbstractCTLMigration { +public class CtlLogMigration extends AbstractCTLMigration { public static final String LOG_SCHEMA_PREFIX_TABLE_NAME = "log"; - public CTLLogMigration(Connection connection) { + public CtlLogMigration(Connection connection) { super(connection); } 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 similarity index 97% rename from server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CTLNotificationMigration.java rename to server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/CtlNotificationMigration.java index c117957852..32d83c8796 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,13 +44,13 @@ import java.util.List; -public class CTLNotificationMigration extends AbstractCTLMigration { +public class CtlNotificationMigration extends AbstractCTLMigration { private MongoClient client; private Cluster cluster; private String dbName; private String nosql; - public CTLNotificationMigration(Connection connection, String host, String db, String nosql) { + public CtlNotificationMigration(Connection connection, String host, String db, String nosql) { super(connection); client = new MongoClient(host); cluster = Cluster.builder() 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 5ba18f47ff..3722312c54 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 @@ -63,7 +63,7 @@ public static void main(String[] args) { options.setDbName(args[i + 1]); break; case "nosql": - options.setNoSQL(args[i + 1]); + options.setNoSql(args[i + 1]); break; case "driver": options.setDriverClassName(args[i + 1]); @@ -85,15 +85,15 @@ public static void main(String[] args) { QueryRunner runner = new QueryRunner(); Long maxId = runner.query(conn, "select max(id) as max_id from base_schems", rs -> rs.next() ? rs.getLong("max_id") : null); BaseSchemaIdCounter.setInitValue(maxId); - UpdateUuidsMigration updateUuidsMigration = new UpdateUuidsMigration(conn, options.getHost(), options.getDbName(), options.getNoSQL()); - EndpointProfileMigration endpointProfileMigration = new EndpointProfileMigration(options.getHost(), options.getDbName(), options.getNoSQL()); + 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<>(); - migrationList.add(new CTLConfigurationMigration(conn)); - migrationList.add(new CTLEventsMigration(conn)); - migrationList.add(new CTLNotificationMigration(conn, options.getHost(), options.getDbName(), options.getNoSQL())); - migrationList.add(new CTLLogMigration(conn)); + migrationList.add(new CtlConfigurationMigration(conn)); + migrationList.add(new CtlEventsMigration(conn)); + migrationList.add(new CtlNotificationMigration(conn, options.getHost(), options.getDbName(), options.getNoSql())); + migrationList.add(new CtlLogMigration(conn)); - CTLAggregation aggregation = new CTLAggregation(conn); + CtlAggregation aggregation = new CtlAggregation(conn); BaseSchemaRecordsCreation recordsCreation = new BaseSchemaRecordsCreation(conn); // convert uuids from latin1 to base64 @@ -122,8 +122,8 @@ public static void main(String[] args) { } conn.commit(); - } catch (SQLException | IOException | ConfigurationGenerationException e) { - LOG.error("Error: " + e.getMessage(), e); + } catch (SQLException | IOException | ConfigurationGenerationException ex) { + LOG.error("Error: " + ex.getMessage(), ex); DbUtils.rollbackAndCloseQuietly(conn); } finally { DbUtils.rollbackAndCloseQuietly(conn); diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/CtlMetaInfo.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/CtlMetaInfo.java index 95d65e1965..053291d3f9 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/CtlMetaInfo.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/model/CtlMetaInfo.java @@ -30,16 +30,25 @@ public CtlMetaInfo(Long id, String fqn, Long appId, Long tenantId) { } @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; + } - CtlMetaInfo that = (CtlMetaInfo) o; + if (obj == null || getClass() != obj.getClass()) { + return false; + } - if (!fqn.equals(that.fqn)) return false; - if (appId != null ? !appId.equals(that.appId) : that.appId != null) return false; - return tenantId != null ? tenantId.equals(that.tenantId) : that.tenantId == null; + CtlMetaInfo that = (CtlMetaInfo) obj; + + if (!fqn.equals(that.fqn)) { + return false; + } + if (appId != null ? !appId.equals(that.appId) : that.appId != null) { + return false; + } + return tenantId != null ? tenantId.equals(that.tenantId) : that.tenantId == null; } @Override diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/DataSources.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/DataSources.java index 847b614d55..466b44f088 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/DataSources.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/DataSources.java @@ -20,7 +20,7 @@ import javax.sql.DataSource; -final public class DataSources { +public final class DataSources { public static DataSource getDataSource(Options opt) { BasicDataSource bds = new BasicDataSource(); diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/Options.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/Options.java index abc2a4867f..99148122d7 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/Options.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/Options.java @@ -17,7 +17,7 @@ package org.kaaproject.kaa.server.datamigration.utils; -final public class Options { +public final class Options { public static final String DEFAULT_USER_NAME = "sqladmin"; public static final String DEFAULT_PASSWORD = "admin"; public static final String DEFAULT_DB_NAME = "kaa"; @@ -30,7 +30,7 @@ final public class Options { private String password = DEFAULT_PASSWORD; private String dbName = DEFAULT_DB_NAME; private String host = DEFAULT_HOST; - private String noSQL = DEFAULT_NO_SQL; + private String noSql = DEFAULT_NO_SQL; private String driverClassName = DEFAULT_DRIVER_CLASS_NAME; private String jdbcUrl = DEFAULT_JDBC_URL; @@ -66,12 +66,12 @@ public void setHost(String host) { this.host = host; } - public String getNoSQL() { - return noSQL; + public String getNoSql() { + return noSql; } - public void setNoSQL(String noSQL) { - this.noSQL = noSQL; + public void setNoSql(String noSql) { + this.noSql = noSql; } public String getDriverClassName() { @@ -92,13 +92,12 @@ public void setJdbcUrl(String jdbcUrl) { @Override public String toString() { - return "Options{" + - "username='" + username + '\'' + - ", password='" + password + '\'' + - ", dbName='" + dbName + '\'' + - ", host='" + host + '\'' + - ", driverClassName='" + driverClassName + '\'' + - ", jdbcUrl='" + jdbcUrl + '\'' + - '}'; + return "Options{" + + "username='" + username + '\'' + + ", password='" + password + '\'' + + ", dbName='" + dbName + '\'' + + ", host='" + host + '\'' + + ", driverClassName='" + driverClassName + '\'' + + ", jdbcUrl='" + jdbcUrl + '\'' + '}'; } } diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/Utils.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/Utils.java index 85fdded3ba..81c0463369 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/Utils.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/Utils.java @@ -22,7 +22,7 @@ import java.io.IOException; import java.util.Base64; -final public class Utils { +public final class Utils { private static final String UUID_FIELD = "__uuid"; private static final String UUID_VALUE = "org.kaaproject.configuration.uuidT"; @@ -30,16 +30,18 @@ final public class Utils { public static JsonNode encodeUuids(JsonNode json) throws IOException { if (json.has(UUID_FIELD)) { - JsonNode j = json.get(UUID_FIELD); - if (j.has(UUID_VALUE)) { - String value = j.get(UUID_VALUE).asText(); + JsonNode jsonNode = json.get(UUID_FIELD); + if (jsonNode.has(UUID_VALUE)) { + String value = jsonNode.get(UUID_VALUE).asText(); String encodedValue = Base64.getEncoder().encodeToString(value.getBytes("ISO-8859-1")); - ((ObjectNode) j).put(UUID_VALUE, encodedValue); + ((ObjectNode) jsonNode).put(UUID_VALUE, encodedValue); } } for (JsonNode node : json) { - if (node.isContainerNode()) encodeUuids(node); + if (node.isContainerNode()) { + encodeUuids(node); + } } return json; diff --git a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/datadefinition/BuilderException.java b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/datadefinition/BuilderException.java index e4efa41f6f..382d60c540 100644 --- a/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/datadefinition/BuilderException.java +++ b/server/upgrade/data-migration-0.9.0-0.10.0/src/main/java/org/kaaproject/kaa/server/datamigration/utils/datadefinition/BuilderException.java @@ -18,7 +18,7 @@ public class BuilderException extends RuntimeException { - public BuilderException(String s) { - super(s); + public BuilderException(String str) { + super(str); } } 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 7fea170273..bbd804c8ce 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 @@ -41,7 +41,7 @@ public AlterBuilder alterTable(String tableName) { * Drop foreign key with autogenerated name based on the table where constrain declared and * referenced table name */ - public void dropUnnamedFK(String tableName, String referencedTableName) throws SQLException { + public void dropUnnamedFk(String tableName, String referencedTableName) throws SQLException { QueryRunner runner = new QueryRunner(); String query = String.format(QUERY_FIND_FK_NAME, tableName, referencedTableName); String fkName = runner.query(connection, query, rs -> rs.next() ? rs.getString(1) : null); @@ -92,6 +92,8 @@ public void execute() throws SQLException { case UNIQUE: sql.append(format("ADD CONSTRAINT %s UNIQUE (%s)\n", c.getConstraintName(), c.getField())); break; + default: + break; } if (i < addConstrains.size() - 1) {