From 28b70aa32be73458cd42359e5c7c2e679d24b300 Mon Sep 17 00:00:00 2001 From: Kirill Liubun Date: Fri, 30 Sep 2016 13:54:06 +0300 Subject: [PATCH] Fix code style --- .../client/async/AvroAsyncRpcClient.java | 34 +++++++------- .../appenders/mongo/appender/LogEvent.java | 35 ++++++++++----- .../mongo/appender/LogEventMongoDao.java | 13 +++--- .../mongo/appender/MongoDbLogAppender.java | 37 +++++++++------ ...HttpComponentsRequestFactoryBasicAuth.java | 35 ++++++++------- .../kaa/server/common/dao/DaoConstants.java | 8 ++-- .../dao/EndpointRegistrationService.java | 15 ++++--- .../common/dao/LogAppendersService.java | 20 --------- .../common/dao/NotificationService.java | 13 ++++-- .../common/dao/UserConfigurationService.java | 34 ++++---------- .../dao/service/LogAppenderServiceImpl.java | 3 +- .../control/service/sdk/SchemaUtil.java | 32 ++++++++----- .../http/transport/HttpHandler.java | 22 ++++----- .../http/transport/HttpTransport.java | 36 ++++++++++----- .../commands/AbstractHttpSyncCommand.java | 45 ++++++++----------- .../http/transport/commands/SyncCommand.java | 5 +-- .../netty/AbstractKaaTcpCommandProcessor.java | 7 +-- 17 files changed, 210 insertions(+), 184 deletions(-) diff --git a/server/appenders/flume-appender/src/main/java/org/kaaproject/kaa/server/appenders/flume/appender/client/async/AvroAsyncRpcClient.java b/server/appenders/flume-appender/src/main/java/org/kaaproject/kaa/server/appenders/flume/appender/client/async/AvroAsyncRpcClient.java index 0a70c25a27..8081601f69 100644 --- a/server/appenders/flume-appender/src/main/java/org/kaaproject/kaa/server/appenders/flume/appender/client/async/AvroAsyncRpcClient.java +++ b/server/appenders/flume-appender/src/main/java/org/kaaproject/kaa/server/appenders/flume/appender/client/async/AvroAsyncRpcClient.java @@ -50,7 +50,8 @@ public AvroAsyncRpcClient(Properties starterProp, int numberOfClientThreads) { } LOG.info("Number of Threads:" + numberOfClientThreads); - executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(numberOfClientThreads)); + executorService = MoreExecutors + .listeningDecorator(Executors.newFixedThreadPool(numberOfClientThreads)); } public AvroAsyncRpcClient(String hostname, Integer port, int numberOfThreads) { @@ -64,18 +65,21 @@ public AvroAsyncRpcClient(String hostname, Integer port, int numberOfThreads) { } LOG.info("Number of Threads:" + numberOfClientThreads); - executorService = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(numberOfClientThreads)); + executorService = MoreExecutors + .listeningDecorator(Executors.newFixedThreadPool(numberOfClientThreads)); } - public ListenableFuture appendAsync(final Event event) throws EventDeliveryException { - ListenableFuture future = executorService.submit(new Callable() { - public AppendAsyncResultPojo call() throws Exception { - RpcClient client = clientQueue.poll(); - client.append(event); - clientQueue.add(client); - return new AppendAsyncResultPojo(true, event); - } - }); + public ListenableFuture appendAsync(final Event event) + throws EventDeliveryException { + ListenableFuture future = executorService.submit( + new Callable() { + public AppendAsyncResultPojo call() throws Exception { + RpcClient client = clientQueue.poll(); + client.append(event); + clientQueue.add(client); + return new AppendAsyncResultPojo(true, event); + } + }); return future; } @@ -103,8 +107,8 @@ public int getBatchSize() { public void append(Event event) throws EventDeliveryException { try { this.appendAsync(event).get(); - } catch (Exception e) { - throw new EventDeliveryException(e); + } catch (Exception ex) { + throw new EventDeliveryException(ex); } } @@ -112,8 +116,8 @@ public void append(Event event) throws EventDeliveryException { public void appendBatch(List events) throws EventDeliveryException { try { this.appendBatchAsync(events).get(); - } catch (Exception e) { - throw new EventDeliveryException(e); + } catch (Exception ex) { + throw new EventDeliveryException(ex); } } diff --git a/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/LogEvent.java b/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/LogEvent.java index 2e4daf1b1f..4663e747de 100644 --- a/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/LogEvent.java +++ b/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/LogEvent.java @@ -16,6 +16,10 @@ package org.kaaproject.kaa.server.appenders.mongo.appender; +import static com.mongodb.util.JSON.parse; +import static org.kaaproject.kaa.server.common.nosql.mongo.dao.model.MongoDaoUtil.decodeReservedCharacteres; +import static org.kaaproject.kaa.server.common.nosql.mongo.dao.model.MongoDaoUtil.encodeReservedCharacteres; + import com.mongodb.DBObject; import com.mongodb.util.JSON; @@ -45,10 +49,13 @@ public LogEvent() { public LogEvent(LogEventDto dto, ProfileInfo clientProfile, ProfileInfo serverProfile) { this.id = dto.getId(); - this.header = MongoDaoUtil.encodeReservedCharacteres((DBObject) JSON.parse(dto.getHeader())); - this.event = MongoDaoUtil.encodeReservedCharacteres((DBObject) JSON.parse(dto.getEvent())); - this.clientProfile = (clientProfile != null) ? MongoDaoUtil.encodeReservedCharacteres((DBObject) JSON.parse(clientProfile.getBody())) : null; - this.serverProfile = (serverProfile != null) ? MongoDaoUtil.encodeReservedCharacteres((DBObject) JSON.parse(serverProfile.getBody())) : null; + this.header = encodeReservedCharacteres((DBObject) parse(dto.getHeader())); + this.event = encodeReservedCharacteres((DBObject) parse(dto.getEvent())); + this.clientProfile = (clientProfile != null) + ? encodeReservedCharacteres((DBObject) parse(clientProfile.getBody())) : null; + + this.serverProfile = (serverProfile != null) + ? encodeReservedCharacteres((DBObject) parse(serverProfile.getBody())) : null; } public String getId() { @@ -64,7 +71,7 @@ public DBObject getEvent() { } public void setEvent(DBObject event) { - this.event = MongoDaoUtil.encodeReservedCharacteres(event); + this.event = encodeReservedCharacteres(event); } public DBObject getHeader() { @@ -72,7 +79,7 @@ public DBObject getHeader() { } public void setHeader(DBObject header) { - this.header = MongoDaoUtil.encodeReservedCharacteres(header); + this.header = encodeReservedCharacteres(header); } public DBObject getClientProfile() { @@ -80,7 +87,7 @@ public DBObject getClientProfile() { } public void setClientProfile(DBObject clientProfile) { - this.clientProfile = MongoDaoUtil.encodeReservedCharacteres(clientProfile); + this.clientProfile = encodeReservedCharacteres(clientProfile); } public DBObject getServerProfile() { @@ -88,15 +95,19 @@ public DBObject getServerProfile() { } public void setServerProfile(DBObject serverProfile) { - this.serverProfile = MongoDaoUtil.encodeReservedCharacteres(serverProfile); + this.serverProfile = encodeReservedCharacteres(serverProfile); } @Override public String toString() { - return "LogEvent [id=" + id + ", header=" + header != null ? MongoDaoUtil.decodeReservedCharacteres(header).toString() : "" + ", event=" + - event != null ? MongoDaoUtil.decodeReservedCharacteres(event).toString() : "" + ", clientProfile=" + - clientProfile != null ? MongoDaoUtil.decodeReservedCharacteres(clientProfile).toString() : "" + ", serverProfile=" + - serverProfile != null ? MongoDaoUtil.decodeReservedCharacteres(serverProfile).toString() : "" + "]"; + final StringBuilder sb = new StringBuilder("LogEvent["); + sb.append("id='").append(id).append('\''); + sb.append(", header=").append(header); + sb.append(", event=").append(event); + sb.append(", clientProfile=").append(clientProfile); + sb.append(", serverProfile=").append(serverProfile); + sb.append(']'); + return sb.toString(); } } diff --git a/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/LogEventMongoDao.java b/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/LogEventMongoDao.java index 88b7ee2154..2f3b852a32 100644 --- a/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/LogEventMongoDao.java +++ b/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/LogEventMongoDao.java @@ -58,7 +58,8 @@ public LogEventMongoDao(MongoDbConfig configuration) throws Exception { List credentials = new ArrayList<>(); if (configuration.getMongoCredentials() != null) { for (MongoDBCredential credential : configuration.getMongoCredentials()) { - credentials.add(MongoCredential.createMongoCRCredential(credential.getUser(), configuration.getDbName(), + credentials.add(MongoCredential.createMongoCRCredential(credential.getUser(), + configuration.getDbName(), credential.getPassword().toCharArray())); } } @@ -85,7 +86,8 @@ public LogEventMongoDao(MongoDbConfig configuration) throws Exception { MongoDbFactory dbFactory = new SimpleMongoDbFactory(mongoClient, configuration.getDbName()); - MappingMongoConverter converter = new MappingMongoConverter(dbFactory, new MongoMappingContext()); + MappingMongoConverter converter = new MappingMongoConverter(dbFactory, + new MongoMappingContext()); converter.setTypeMapper(new DefaultMongoTypeMapper(null)); mongoTemplate = new MongoTemplate(dbFactory, converter); @@ -98,13 +100,14 @@ public void createCollection(String collectionName) { if (!mongoTemplate.collectionExists(collectionName)) { mongoTemplate.createCollection(collectionName); } - } catch (UncategorizedMongoDbException e) { - LOG.warn("Failed to create collection {} due to", collectionName, e); + } catch (UncategorizedMongoDbException ex) { + LOG.warn("Failed to create collection {} due to", collectionName, ex); } } @Override - public List save(List logEventDtos, ProfileInfo clientProfile, ProfileInfo serverProfile, String collectionName) { + public List save(List logEventDtos, ProfileInfo clientProfile, + ProfileInfo serverProfile, String collectionName) { List logEvents = new ArrayList<>(logEventDtos.size()); for (LogEventDto logEventDto : logEventDtos) { logEvents.add(new LogEvent(logEventDto, clientProfile, serverProfile)); diff --git a/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/MongoDbLogAppender.java b/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/MongoDbLogAppender.java index f082f77988..2ebe798344 100644 --- a/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/MongoDbLogAppender.java +++ b/server/appenders/mongo-appender/src/main/java/org/kaaproject/kaa/server/appenders/mongo/appender/MongoDbLogAppender.java @@ -50,28 +50,39 @@ public MongoDbLogAppender() { } @Override - public void doAppend(LogEventPack logEventPack, RecordHeader header, LogDeliveryCallback listener) { + public void doAppend(LogEventPack logEventPack, RecordHeader header, + LogDeliveryCallback listener) { if (!closed) { try { - ProfileInfo clientProfile = (this.includeClientProfile) ? logEventPack.getClientProfile() : null; - ProfileInfo serverProfile = (this.includeServerProfile) ? logEventPack.getServerProfile() : null; + ProfileInfo clientProfile = (this.includeClientProfile) + ? logEventPack.getClientProfile() : null; + + ProfileInfo serverProfile = (this.includeServerProfile) + ? logEventPack.getServerProfile() : null; + + LOG.debug("[{}] appending {} logs to mongodb collection", + collectionName, logEventPack.getEvents().size()); - LOG.debug("[{}] appending {} logs to mongodb collection", collectionName, logEventPack.getEvents().size()); List dtos = generateLogEvent(logEventPack, header); LOG.debug("[{}] saving {} objects", collectionName, dtos.size()); if (!dtos.isEmpty()) { logEventDao.save(dtos, clientProfile, serverProfile, collectionName); - LOG.debug("[{}] appended {} logs to mongodb collection", collectionName, logEventPack.getEvents().size()); + + LOG.debug("[{}] appended {} logs to mongodb collection", + collectionName, logEventPack.getEvents().size()); } listener.onSuccess(); - } catch (MongoSocketException e) { - LOG.error(MessageFormat.format("[{0}] Attempted to append logs failed due to network error", getName()), e); + } catch (MongoSocketException ex) { + LOG.error(MessageFormat.format("[{0}] Attempted to append logs failed " + + "due to network error", getName()), ex); listener.onConnectionError(); - } catch (MongoInternalException | MongoServerException e) { - LOG.error(MessageFormat.format("[{0}] Attempted to append logs failed due to remote error", getName()), e); + } catch (MongoInternalException | MongoServerException ex) { + LOG.error(MessageFormat.format("[{0}] Attempted to append logs failed " + + "due to remote error", getName()), ex); listener.onRemoteError(); - } catch (Exception e) { - LOG.error(MessageFormat.format("[{0}] Attempted to append logs failed due to internal error", getName()), e); + } catch (Exception ex) { + LOG.error(MessageFormat.format("[{0}] Attempted to append logs failed " + + "due to internal error", getName()), ex); listener.onInternalError(); } } else { @@ -88,8 +99,8 @@ protected void initFromConfiguration(LogAppenderDto appender, MongoDbConfig conf this.includeClientProfile = configuration.getIncludeClientProfile(); this.includeServerProfile = configuration.getIncludeServerProfile(); createCollection(appender.getApplicationToken()); - } catch (Exception e) { - LOG.error("Failed to init MongoDB log appender: ", e); + } catch (Exception ex) { + LOG.error("Failed to init MongoDB log appender: ", ex); } } diff --git a/server/common/admin-rest-client/src/main/java/org/kaaproject/kaa/server/common/admin/HttpComponentsRequestFactoryBasicAuth.java b/server/common/admin-rest-client/src/main/java/org/kaaproject/kaa/server/common/admin/HttpComponentsRequestFactoryBasicAuth.java index d303632880..5e49a1135f 100644 --- a/server/common/admin-rest-client/src/main/java/org/kaaproject/kaa/server/common/admin/HttpComponentsRequestFactoryBasicAuth.java +++ b/server/common/admin-rest-client/src/main/java/org/kaaproject/kaa/server/common/admin/HttpComponentsRequestFactoryBasicAuth.java @@ -41,10 +41,10 @@ import java.io.IOException; import java.net.URI; -public class HttpComponentsRequestFactoryBasicAuth extends - HttpComponentsClientHttpRequestFactory { +public class HttpComponentsRequestFactoryBasicAuth extends HttpComponentsClientHttpRequestFactory { - private static final Logger LOG = LoggerFactory.getLogger(HttpComponentsRequestFactoryBasicAuth.class); + private static final Logger LOG = LoggerFactory + .getLogger(HttpComponentsRequestFactoryBasicAuth.class); private static final int DEFAULT_MAX_TOTAL_CONNECTIONS = 100; @@ -62,12 +62,12 @@ public HttpComponentsRequestFactoryBasicAuth(HttpHost host) { } private static HttpClient createHttpClient() { - CloseableHttpClient httpClient = HttpClientBuilder.create(). - setMaxConnTotal(DEFAULT_MAX_TOTAL_CONNECTIONS). - setMaxConnPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE). - setRetryHandler(new BasicHttpRequestRetryHandler(5, 10000)). - setServiceUnavailableRetryStrategy(new BaseServiceUnavailableRetryStrategy(3, 5000)). - build(); + CloseableHttpClient httpClient = HttpClientBuilder.create() + .setMaxConnTotal(DEFAULT_MAX_TOTAL_CONNECTIONS) + .setMaxConnPerRoute(DEFAULT_MAX_CONNECTIONS_PER_ROUTE) + .setRetryHandler(new BasicHttpRequestRetryHandler(5, 10000)) + .setServiceUnavailableRetryStrategy(new BaseServiceUnavailableRetryStrategy(3, 5000)) + .build(); return httpClient; } @@ -95,7 +95,7 @@ public void setCredentials(String username, String password) { new UsernamePasswordCredentials(username, password)); } - static class BasicHttpRequestRetryHandler extends DefaultHttpRequestRetryHandler { + private static class BasicHttpRequestRetryHandler extends DefaultHttpRequestRetryHandler { private final long connectRetryInterval; @@ -109,9 +109,11 @@ public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount <= getRetryCount()) { try { - LOG.warn("IOException '{}'. Wait for {} before next attempt to connect...", exception.getMessage(), connectRetryInterval); + LOG.warn("IOException '{}'. Wait for {} before next attempt to connect...", + exception.getMessage(), connectRetryInterval); Thread.sleep(connectRetryInterval); - } catch (InterruptedException e) { + } catch (InterruptedException ex) { + LOG.error("Thread was interrupted", ex); } return true; } else { @@ -121,7 +123,8 @@ public boolean retryRequest(IOException exception, int executionCount, } - static class BaseServiceUnavailableRetryStrategy implements ServiceUnavailableRetryStrategy { + private static class BaseServiceUnavailableRetryStrategy + implements ServiceUnavailableRetryStrategy { /** * Maximum number of allowed retries if the server responds with a HTTP code @@ -151,8 +154,10 @@ public BaseServiceUnavailableRetryStrategy() { this(1, 1000); } - public boolean retryRequest(final HttpResponse response, int executionCount, final HttpContext context) { - return executionCount <= maxRetries && response.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE; + public boolean retryRequest(final HttpResponse response, int executionCount, + final HttpContext context) { + return executionCount <= maxRetries + && response.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE; } public long getRetryInterval() { diff --git a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/DaoConstants.java b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/DaoConstants.java index 78bdd9dcd4..6ab9459efc 100644 --- a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/DaoConstants.java +++ b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/DaoConstants.java @@ -358,7 +358,7 @@ public class DaoConstants { public static final String LOG_SCHEMA_TABLE_NAME = "log_schems"; /** - * Notification schems constants + * Notification schems constants. */ public static final String NOTIFICATION_SCHEMA_TABLE_NAME = "notification_schems"; public static final String NOTIFICATION_SCHEMA_TYPE_PROPERTY = "type"; @@ -372,7 +372,7 @@ public class DaoConstants { public static final String LOG_APPENDER_CONFIRM_DELIVERY = "confirm_delivery"; /** - * SDK profile constants + * SDK profile constants. */ public static final String SDK_PROFILE_APPLICATION_ID = APPLICATION_ID; public static final String SDK_PROFILE_CONFIGURATION_SCHEMA_VERSION = @@ -390,7 +390,7 @@ public class DaoConstants { public static final String SDK_PROFILE_TOKEN = "token"; /** - * CTL schems constants + * CTL schems constants. */ public static final String CTL_SCHEMA_TABLE_NAME = "ctl"; public static final String CTL_SCHEMA_META_INFO_ID = "metainfo_id"; @@ -415,7 +415,7 @@ public class DaoConstants { + "." + ID; /** - * CTL schems meta info constants + * CTL schems meta info constants. */ public static final String CTL_SCHEMA_META_INFO_TABLE_NAME = "ctl_metainfo"; public static final String CTL_SCHEMA_META_INFO_FQN = FQN; diff --git a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/EndpointRegistrationService.java b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/EndpointRegistrationService.java index 6e719f16e9..eb70eb0f44 100644 --- a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/EndpointRegistrationService.java +++ b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/EndpointRegistrationService.java @@ -37,7 +37,8 @@ public interface EndpointRegistrationService { * @return The endpoint registration saved * @throws EndpointRegistrationServiceException - if an exception occurs. */ - EndpointRegistrationDto saveEndpointRegistration(EndpointRegistrationDto endpointRegistration) throws EndpointRegistrationServiceException; + EndpointRegistrationDto saveEndpointRegistration(EndpointRegistrationDto endpointRegistration) + throws EndpointRegistrationServiceException; /** * Returns the endpoint registration by the endpoint ID specified. @@ -46,7 +47,8 @@ public interface EndpointRegistrationService { * @return The endpoint registration found * @throws EndpointRegistrationServiceException - if an exception occurs. */ - Optional findEndpointRegistrationByEndpointId(String endpointId) throws EndpointRegistrationServiceException; + Optional findEndpointRegistrationByEndpointId(String endpointId) + throws EndpointRegistrationServiceException; /** * Returns the endpoint registration by the credentials ID specified. @@ -55,7 +57,8 @@ public interface EndpointRegistrationService { * @return The endpoint registration found * @throws EndpointRegistrationServiceException - if an exception occurs. */ - Optional findEndpointRegistrationByCredentialsId(String credentialsId) throws EndpointRegistrationServiceException; + Optional findEndpointRegistrationByCredentialsId(String credentialsId) + throws EndpointRegistrationServiceException; /** * Removes the endpoint registration by the endpoint ID specified. @@ -63,7 +66,8 @@ public interface EndpointRegistrationService { * @param endpointId The endpoint ID * @throws EndpointRegistrationServiceException - if an exception occurs. */ - void removeEndpointRegistrationByEndpointId(String endpointId) throws EndpointRegistrationServiceException; + void removeEndpointRegistrationByEndpointId(String endpointId) + throws EndpointRegistrationServiceException; /** * Removes the endpoint registration by the registration ID specified. @@ -71,5 +75,6 @@ public interface EndpointRegistrationService { * @param registrationId The registration ID * @throws EndpointRegistrationServiceException - if an exception occurs. */ - void removeEndpointRegistrationById(String registrationId) throws EndpointRegistrationServiceException; + void removeEndpointRegistrationById(String registrationId) + throws EndpointRegistrationServiceException; } diff --git a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/LogAppendersService.java b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/LogAppendersService.java index b24f7ed5ca..bf3119c131 100644 --- a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/LogAppendersService.java +++ b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/LogAppendersService.java @@ -39,34 +39,14 @@ public interface LogAppendersService { - /** - * @param appId the app id - * @return the list log appender dto - */ List findAllAppendersByAppId(String appId); - /** - * @param appId the app id - * @param schemaVersion the schema version - * @return the list log appender dto - */ List findLogAppendersByAppIdAndSchemaVersion(String appId, int schemaVersion); - /** - * @param id the id - */ void removeLogAppenderById(String id); - /** - * @param id the id - * @return the log appender dto - */ LogAppenderDto findLogAppenderById(String id); - /** - * @param logAppenderDto the log appender dto - * @return the log appender dto - */ LogAppenderDto saveLogAppender(LogAppenderDto logAppenderDto); } diff --git a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/NotificationService.java b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/NotificationService.java index 643eef688d..8e80488b47 100644 --- a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/NotificationService.java +++ b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/NotificationService.java @@ -68,7 +68,8 @@ public interface NotificationService { * @param dto the dto * @return the update notification dto */ - UpdateNotificationDto saveUnicastNotification(EndpointNotificationDto dto); + UpdateNotificationDto saveUnicastNotification( + EndpointNotificationDto dto); /** * Find notifications by topic id. @@ -128,7 +129,8 @@ public interface NotificationService { * @param userNfVersion the user schema version * @return the list */ - List findNotificationsByTopicIdAndVersionAndStartSecNum(String topicId, int seqNum, int sysNfVersion, int userNfVersion); + List findNotificationsByTopicIdAndVersionAndStartSecNum( + String topicId, int seqNum, int sysNfVersion, int userNfVersion); /** * Find notification schemas by app id and type. @@ -137,7 +139,8 @@ public interface NotificationService { * @param type the type * @return the list */ - List findNotificationSchemasByAppIdAndType(String appId, NotificationTypeDto type); + List findNotificationSchemasByAppIdAndType(String appId, + NotificationTypeDto type); /** * Find notification schema by app id and type and version. @@ -147,7 +150,9 @@ public interface NotificationService { * @param majorVersion the major version * @return the notification schema dto */ - NotificationSchemaDto findNotificationSchemaByAppIdAndTypeAndVersion(String appId, NotificationTypeDto type, int majorVersion); + NotificationSchemaDto findNotificationSchemaByAppIdAndTypeAndVersion(String appId, + NotificationTypeDto type, + int majorVersion); /** * Find unicast notifications by key hash. diff --git a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/UserConfigurationService.java b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/UserConfigurationService.java index 0de69746c4..6935377dd2 100644 --- a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/UserConfigurationService.java +++ b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/UserConfigurationService.java @@ -21,37 +21,21 @@ import java.util.List; /** - * Provides methods to operate with {@link EndpointUserConfigurationDto} + * Provides methods to operate with {@link EndpointUserConfigurationDto}. */ public interface UserConfigurationService { - /** - * @param dto the dto - * @return the endpoint user configuration dto - */ + EndpointUserConfigurationDto saveUserConfiguration(EndpointUserConfigurationDto dto); - /** - * @param userId the user id - * @param appToken the app token - * @param schemaVersion the schema version - * @return the endpoint user configuration dto - */ - EndpointUserConfigurationDto findUserConfigurationByUserIdAndAppTokenAndSchemaVersion(String userId, String appToken, Integer schemaVersion); - - /** - * @param userId the user id - * @return the list endpoint user configuration dto - */ - List findUserConfigurationByUserId(String userId); + EndpointUserConfigurationDto findUserConfigurationByUserIdAndAppTokenAndSchemaVersion( + String userId, String appToken, Integer schemaVersion); - /** - * @param userId the user id - * @param appToken the app token - * @param schemaVersion the schema version - */ - void removeByUserIdAndAppTokenAndSchemaVersion(String userId, String appToken, Integer schemaVersion); + List findUserConfigurationByUserId(String userId); + void removeByUserIdAndAppTokenAndSchemaVersion(String userId, + String appToken, Integer schemaVersion); - EndpointUserConfigurationDto findUserConfigurationByExternalUIdAndAppTokenAndSchemaVersion(String externalUId, String appToken, Integer schemaVersion, String tenantId); + EndpointUserConfigurationDto findUserConfigurationByExternalUIdAndAppTokenAndSchemaVersion( + String externalUId, String appToken, Integer schemaVersion, String tenantId); } diff --git a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/service/LogAppenderServiceImpl.java b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/service/LogAppenderServiceImpl.java index 8f5f3d6161..a579dcded2 100644 --- a/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/service/LogAppenderServiceImpl.java +++ b/server/common/dao/src/main/java/org/kaaproject/kaa/server/common/dao/service/LogAppenderServiceImpl.java @@ -48,7 +48,8 @@ public class LogAppenderServiceImpl implements LogAppendersService { @Override public List findLogAppendersByAppIdAndSchemaVersion( String appId, int schemaVersion) { - LOG.debug("Find registered log appenders by application id [{}] and schema version [{}]", appId, schemaVersion); + LOG.debug("Find registered log appenders by application id [{}] and schema version [{}]", + appId, schemaVersion); return convertDtoList(logAppenderDao.findByAppIdAndSchemaVersion(appId, schemaVersion)); } diff --git a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/SchemaUtil.java b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/SchemaUtil.java index ce28868489..513e823165 100755 --- a/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/SchemaUtil.java +++ b/server/node/src/main/java/org/kaaproject/kaa/server/control/service/sdk/SchemaUtil.java @@ -78,8 +78,8 @@ private static boolean isEqualEnums(Schema s1, Schema s2) { private static boolean isEqualUnions(Schema s1, Schema s2) { - SortedMap types1 = new TreeMap(); - SortedMap types2 = new TreeMap(); + SortedMap types1 = new TreeMap<>(); + SortedMap types2 = new TreeMap<>(); for (Schema schema : s1.getTypes()) { types1.put(schema.getName(), schema); @@ -96,8 +96,8 @@ private static boolean isEqualRecords(Schema s1, Schema s2) { return false; } - SortedMap fields1 = new TreeMap(); - SortedMap fields2 = new TreeMap(); + SortedMap fields1 = new TreeMap<>(); + SortedMap fields2 = new TreeMap<>(); for (Schema.Field field : s1.getFields()) { fields1.put(field.name(), field.schema()); @@ -109,7 +109,8 @@ private static boolean isEqualRecords(Schema s1, Schema s2) { return isEqualSchemaMaps(fields1, fields2); } - private static boolean isEqualSchemaMaps(SortedMap map1, SortedMap map2) { + private static boolean isEqualSchemaMaps(SortedMap map1, + SortedMap map2) { if (!map1.keySet().equals(map2.keySet())) { return false; } @@ -121,10 +122,11 @@ private static boolean isEqualSchemaMaps(SortedMap map1, SortedM return true; } - public static Map getUniqueSchemasMap(Collection schemas) throws Exception { - Map map = new HashMap(); + public static Map getUniqueSchemasMap(Collection schemas) + throws Exception { + Map map = new HashMap<>(); - List allPossible = new LinkedList(); + List allPossible = new LinkedList<>(); for (Schema schema : schemas) { allPossible.addAll(getChildSchemas(schema)); @@ -137,8 +139,10 @@ public static Map getUniqueSchemasMap(Collection schemas map.put(key, schema); } else { if (!SchemaUtil.isEqualSchemas(schema, map.get(key))) { - LOG.debug("classes {} are not the same: \n{}\n\n{}", key, schema.toString(), map.get(key).toString()); - throw new IllegalArgumentException("multiple occurrences of " + key + " with different fields"); + LOG.debug("classes {} are not the same: \n{}\n\n{}", + key, schema.toString(), map.get(key).toString()); + throw new IllegalArgumentException("multiple occurrences of " + + key + " with different fields"); } } } @@ -185,8 +189,12 @@ private static void parseChildSchemas(Schema parent, Map namedSc public static Collection compileAvroSchema(Schema avroSchema) { try { LOG.debug("Compiling {}", avroSchema); - Map uniqueSchemas = SchemaUtil.getUniqueSchemasMap(Collections.singletonList(avroSchema)); - List javaSources = JavaSdkGenerator.generateSchemaSources(avroSchema, uniqueSchemas); + Map uniqueSchemas = SchemaUtil + .getUniqueSchemasMap(Collections.singletonList(avroSchema)); + + List javaSources = JavaSdkGenerator + .generateSchemaSources(avroSchema, uniqueSchemas); + JavaDynamicCompiler compiler = new JavaDynamicCompiler(); compiler.init(); return compiler.compile(javaSources); diff --git a/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/HttpHandler.java b/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/HttpHandler.java index 1df98291da..12d32ff32f 100644 --- a/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/HttpHandler.java +++ b/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/HttpHandler.java @@ -40,18 +40,14 @@ import java.security.GeneralSecurityException; import java.util.UUID; -/** - * The Class AkkaHandler. - */ -public class HttpHandler extends SimpleChannelInboundHandler implements MessageBuilder, ErrorBuilder { + +public class HttpHandler extends SimpleChannelInboundHandler + implements MessageBuilder, ErrorBuilder { private static final Logger LOG = LoggerFactory.getLogger(HttpHandler.class); private final MessageHandler messageHandler; - /** - * The uuid. - */ private final UUID uuid; private volatile AbstractHttpSyncCommand command; @@ -77,10 +73,12 @@ public HttpHandler(UUID uuid, MessageHandler messageHandler) { * org.kaaproject.kaa.server.common.http.server.CommandProcessor) */ @Override - protected void channelRead0(final ChannelHandlerContext ctx, final AbstractCommand msg) throws Exception { + protected void channelRead0(final ChannelHandlerContext ctx, final AbstractCommand msg) + throws Exception { this.command = (AbstractHttpSyncCommand) msg; - NettyHttpSyncMessage message = new NettyHttpSyncMessage(uuid, msg.getNextProtocol(), new NettyChannelContext(ctx), - command.getChannelType(), command, this, this); + NettyHttpSyncMessage message = new NettyHttpSyncMessage(uuid, msg.getNextProtocol(), + new NettyChannelContext(ctx), command.getChannelType(), + command, this, this); LOG.trace("Forwarding {} to handler", message); messageHandler.process(message); } @@ -92,7 +90,9 @@ public Object[] build(Exception exception) { status = HttpResponseStatus.UNAUTHORIZED; } else if (exception instanceof EndpointRevocationException) { status = HttpResponseStatus.FORBIDDEN; - } else if (exception instanceof GeneralSecurityException || exception instanceof IOException || exception instanceof IllegalArgumentException + } else if (exception instanceof GeneralSecurityException + || exception instanceof IOException + || exception instanceof IllegalArgumentException || exception instanceof InvalidSdkTokenException) { status = HttpResponseStatus.BAD_REQUEST; } else { diff --git a/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/HttpTransport.java b/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/HttpTransport.java index 4b44efcb77..428c69612c 100644 --- a/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/HttpTransport.java +++ b/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/HttpTransport.java @@ -45,7 +45,7 @@ import java.util.UUID; /** - * Implementation of Kaa http transport + * Implementation of Kaa http transport. * * @author Andrew Shvayka */ @@ -57,19 +57,33 @@ public class HttpTransport extends AbstractKaaTransport { private AbstractNettyServer netty; @Override - public void init(SpecificTransportContext context) throws TransportLifecycleException { + public void init(SpecificTransportContext context) + throws TransportLifecycleException { AvroHttpConfig configuration = context.getConfiguration(); - configuration.setBindInterface(replaceProperty(configuration.getBindInterface(), BIND_INTERFACE_PROP_NAME, context - .getCommonProperties().getProperty(BIND_INTERFACE_PROP_NAME, LOCALHOST))); - configuration.setPublicInterface(replaceProperty(configuration.getPublicInterface(), PUBLIC_INTERFACE_PROP_NAME, context - .getCommonProperties().getProperty(PUBLIC_INTERFACE_PROP_NAME, LOCALHOST))); - List> processors = new ArrayList>(); + configuration.setBindInterface( + replaceProperty( + configuration.getBindInterface(), + BIND_INTERFACE_PROP_NAME, + context.getCommonProperties().getProperty(BIND_INTERFACE_PROP_NAME, LOCALHOST) + ) + ); + + configuration.setPublicInterface( + replaceProperty( + configuration.getPublicInterface(), + PUBLIC_INTERFACE_PROP_NAME, + context.getCommonProperties().getProperty(PUBLIC_INTERFACE_PROP_NAME, LOCALHOST) + ) + ); + + List> processors = new ArrayList<>(); processors.add(new SyncCommandFactory()); processors.add(new LongSyncCommandFactory()); final CommandFactory factory = new CommandFactory<>(processors); final int maxBodySize = configuration.getMaxBodySize(); - this.netty = new AbstractNettyServer(configuration.getBindInterface(), configuration.getBindPort()) { + this.netty = new AbstractNettyServer(configuration.getBindInterface(), + configuration.getBindPort()) { @Override protected ChannelInitializer configureInitializer() throws Exception { @@ -116,11 +130,13 @@ public Class getConfigurationClass() { protected List getSerializedConnectionInfoList() { List connectionInfoList = new ArrayList<>(); RangeExpressionParser rangeExpressionParser = new RangeExpressionParser(); - List publicPorts = rangeExpressionParser.getNumbersFromRanges(context.getConfiguration().getPublicPorts()); + List publicPorts = rangeExpressionParser + .getNumbersFromRanges(context.getConfiguration().getPublicPorts()); for (int publicPort : publicPorts) { byte[] interfaceData = toUtf8Bytes(context.getConfiguration().getPublicInterface()); byte[] publicKeyData = context.getServerKey().getEncoded(); - ByteBuffer buf = ByteBuffer.wrap(new byte[SIZE_OF_INT * 3 + interfaceData.length + publicKeyData.length]); + ByteBuffer buf = ByteBuffer.wrap( + new byte[SIZE_OF_INT * 3 + interfaceData.length + publicKeyData.length]); buf.putInt(publicKeyData.length); buf.put(publicKeyData); buf.putInt(interfaceData.length); diff --git a/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/commands/AbstractHttpSyncCommand.java b/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/commands/AbstractHttpSyncCommand.java index a445d52186..4892dfaa06 100644 --- a/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/commands/AbstractHttpSyncCommand.java +++ b/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/commands/AbstractHttpSyncCommand.java @@ -21,6 +21,7 @@ import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE; import static io.netty.handler.codec.http.HttpResponseStatus.OK; import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1; +import static org.apache.commons.codec.binary.Base64.encodeBase64String; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; @@ -49,37 +50,22 @@ import java.util.Arrays; import java.util.List; -/** - * The Class AbstractOperationsCommand. - * - * @param the generic type - * @param the generic type - */ + public abstract class AbstractHttpSyncCommand extends AbstractCommand { - /** - * The signature. - */ + private byte[] requestSignature; - /** - * The encoded request session key. - */ + private byte[] requestKey; - /** - * The request data. - */ + private byte[] requestData; - /** - * The response body. - */ + private byte[] responseBody; - /** - * The signature. - */ + private byte[] responseSignature; private int nextProtocol = Constants.KAA_PLATFORM_PROTOCOL_AVRO_ID; @@ -125,7 +111,8 @@ public void parse() throws Exception { if (CommonEpConstans.REQUEST_SIGNATURE_ATTR_NAME.equals(data.getName())) { requestSignature = attribute.get(); if (LOG.isTraceEnabled()) { - LOG.trace("Multipart name " + data.getName() + " type " + data.getHttpDataType().name() + " Signature set. size: " + LOG.trace("Multipart name " + data.getName() + " type " + + data.getHttpDataType().name() + " Signature set. size: " + requestSignature.length); LOG.trace(MessageEncoderDecoder.bytesToHex(requestSignature)); } @@ -133,14 +120,16 @@ public void parse() throws Exception { } else if (CommonEpConstans.REQUEST_KEY_ATTR_NAME.equals(data.getName())) { requestKey = attribute.get(); if (LOG.isTraceEnabled()) { - LOG.trace("Multipart name " + data.getName() + " type " + data.getHttpDataType().name() + " requestKey set. size: " + LOG.trace("Multipart name " + data.getName() + " type " + + data.getHttpDataType().name() + " requestKey set. size: " + requestKey.length); LOG.trace(MessageEncoderDecoder.bytesToHex(requestKey)); } } else if (CommonEpConstans.REQUEST_DATA_ATTR_NAME.equals(data.getName())) { requestData = attribute.get(); if (LOG.isTraceEnabled()) { - LOG.trace("Multipart name " + data.getName() + " type " + data.getHttpDataType().name() + " requestData set. size: " + LOG.trace("Multipart name " + data.getName() + " type " + + data.getHttpDataType().name() + " requestData set. size: " + requestData.length); LOG.trace(MessageEncoderDecoder.bytesToHex(requestData)); } @@ -212,9 +201,13 @@ public HttpResponse getResponse() { httpResponse.headers().set(CONTENT_TYPE, CommonEpConstans.RESPONSE_CONTENT_TYPE); httpResponse.headers().set(CONTENT_LENGTH, data.readableBytes()); LOG.warn("Response size: {}", data.readableBytes()); - httpResponse.headers().set(CommonEpConstans.RESPONSE_TYPE, CommonEpConstans.RESPONSE_TYPE_OPERATION); + httpResponse + .headers() + .set(CommonEpConstans.RESPONSE_TYPE, CommonEpConstans.RESPONSE_TYPE_OPERATION); if (responseSignature != null) { - httpResponse.headers().set(CommonEpConstans.SIGNATURE_HEADER_NAME, Base64.encodeBase64String(responseSignature)); + httpResponse + .headers() + .set(CommonEpConstans.SIGNATURE_HEADER_NAME, encodeBase64String(responseSignature)); } if (isNeedConnectionClose()) { httpResponse.headers().set(CONNECTION, HttpHeaders.Values.CLOSE); diff --git a/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/commands/SyncCommand.java b/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/commands/SyncCommand.java index 183d1e57ee..24c634f437 100644 --- a/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/commands/SyncCommand.java +++ b/server/transports/http/transport/src/main/java/org/kaaproject/kaa/server/transports/http/transport/commands/SyncCommand.java @@ -17,14 +17,13 @@ /** * */ + package org.kaaproject.kaa.server.transports.http.transport.commands; import org.kaaproject.kaa.common.endpoint.CommonEpConstans; import org.kaaproject.kaa.server.transport.channel.ChannelType; -/** - * The Class SyncCommand. - */ + public class SyncCommand extends AbstractHttpSyncCommand implements CommonEpConstans { /** diff --git a/server/transports/tcp/transport/src/main/java/org/kaaproject/kaa/server/transports/tcp/transport/netty/AbstractKaaTcpCommandProcessor.java b/server/transports/tcp/transport/src/main/java/org/kaaproject/kaa/server/transports/tcp/transport/netty/AbstractKaaTcpCommandProcessor.java index 454a653f76..b0ec559bb7 100644 --- a/server/transports/tcp/transport/src/main/java/org/kaaproject/kaa/server/transports/tcp/transport/netty/AbstractKaaTcpCommandProcessor.java +++ b/server/transports/tcp/transport/src/main/java/org/kaaproject/kaa/server/transports/tcp/transport/netty/AbstractKaaTcpCommandProcessor.java @@ -19,15 +19,16 @@ import org.kaaproject.kaa.common.channels.protocols.kaatcp.messages.MqttFrame; import org.kaaproject.kaa.server.common.server.KaaCommandProcessor; -public abstract class AbstractKaaTcpCommandProcessor implements KaaCommandProcessor { +public abstract class AbstractKaaTcpCommandProcessor + implements KaaCommandProcessor { /** - * Time of SYNC processing + * Time of SYNC processing. */ private long syncTime = 0; /** - * integer representing ID of HTTP request + * Integer representing id of HTTP request. */ private int commandId;