From 7ff68e4dae72c8b02e373f6728869cb749e07a1b Mon Sep 17 00:00:00 2001 From: anton Date: Wed, 25 Mar 2020 02:08:27 +0300 Subject: [PATCH 1/6] fix recreating loggers refactoring of lazy values fix #211 fix #210 fix #232 --- .../AgileConfigurationsActivator.java | 23 +- .../http/HttpServerAgileConfiguration.java | 2 +- .../TarantoolAgileConfiguration.java | 1 + .../tarantool/TarantoolConfigKeys.java | 1 + ...emoteConfigCommunicationSpecification.java | 3 +- .../ru/art/config/module/ConfigModule.java | 5 +- ...onfiguratorCommunicationSpecification.java | 6 +- .../ConfiguratorHttpServerConfiguration.java | 4 +- .../module/ConfiguratorModule.java | 5 +- .../ru/art/core/constants/ContextState.java | 1 - .../java/ru/art/core/context/Context.java | 45 +- .../java/ru/art/entity/CollectionValue.java | 408 ++++++++++-------- .../GrpcCommunicatorChannelFactory.java | 7 +- .../GrpcCommunicatorImplementation.java | 15 +- .../GrpcClientModuleConfiguration.java | 8 +- .../GrpcClientLoggingInterceptor.java | 26 +- .../grpc/client/module/GrpcClientModule.java | 7 +- .../java/ru/art/grpc/server/GrpcServer.java | 16 +- .../GrpcServerModuleConfiguration.java | 2 +- .../GrpcServerLoggingInterceptor.java | 23 +- .../HttpCommunicationExecutor.java | 12 +- .../HttpCommunicatorImplementation.java | 9 +- .../HttpClientModuleConfiguration.java | 87 ++-- .../constants/HttpClientModuleConstants.java | 2 +- .../client/factory/HttpClientsFactory.java | 55 +-- .../http/client/module/HttpClientModule.java | 11 +- .../java/ru/art/http/server/HttpServer.java | 52 ++- .../server/HttpServerModuleConfiguration.java | 13 +- .../HttpResourceServiceSpecification.java | 4 +- .../HttpModuleConfiguration.java | 4 +- .../http/logger/ZalangoLogbookLogWriter.java | 14 +- .../information/module/InformationModule.java | 3 +- .../web/src/component/EntityComponent.tsx | 25 +- .../src/component/GrpcServiceComponent.tsx | 4 +- .../consumer/module/KafkaConsumerModule.java | 22 +- .../registry/KafkaStreamsRegistry.java | 4 +- .../logging/LoggerConfigurationService.java | 4 + .../art/logging/LoggingModuleConstants.java | 1 + .../art/logging/LoggingValueInterceptor.java | 15 +- .../logging/SocketAppenderConfiguration.java | 1 + .../http/filter/MetricsHttpLogFilter.java | 9 +- .../manager/module/NetworkManagerModule.java | 5 +- .../service/module/ReactiveServiceModule.java | 3 +- .../action/TaskExecutionActions.java | 18 +- .../communicator/RsocketCommunicator.java | 14 +- .../RsocketModuleConfiguration.java | 4 +- .../RsocketLoggingInterceptor.java | 58 ++- .../rsocket/model/RsocketRequestContext.java | 6 +- .../ru/art/rsocket/module/RsocketModule.java | 35 +- .../ru/art/rsocket/server/RsocketServer.java | 23 +- .../writer/ServiceResponsePayloadWriter.java | 9 +- .../service/ServiceLoggingInterception.java | 5 +- .../grpc/LockServiceProxySpecification.java | 5 +- .../NetworkServiceProxySpecification.java | 11 +- .../state/module/ApplicationStateModule.java | 5 +- .../TarantoolConnectionConfiguration.java | 2 + .../connector/TarantoolConnector.java | 24 +- .../executor/TarantoolLuaExecutor.java | 8 +- .../initializer/TarantoolInitializer.java | 47 +- .../art/tarantool/module/TarantoolModule.java | 3 +- 60 files changed, 672 insertions(+), 572 deletions(-) diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/activator/AgileConfigurationsActivator.java b/application-config-extensions/src/main/java/ru/art/config/extensions/activator/AgileConfigurationsActivator.java index 2287d1a29..c6be2b49e 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/activator/AgileConfigurationsActivator.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/activator/AgileConfigurationsActivator.java @@ -19,8 +19,8 @@ package ru.art.config.extensions.activator; import lombok.experimental.*; +import org.apache.logging.log4j.*; import ru.art.config.extensions.provider.*; -import ru.art.config.remote.provider.*; import ru.art.core.annotation.*; import ru.art.core.configuration.ContextInitialConfiguration.*; import ru.art.core.context.*; @@ -28,10 +28,10 @@ import static ru.art.config.ConfigProvider.*; import static ru.art.config.module.ConfigModule.*; import static ru.art.config.remote.constants.RemoteConfigLoaderConstants.*; +import static ru.art.config.remote.provider.RemoteConfigProvider.*; import static ru.art.core.checker.CheckerForEmptiness.*; import static ru.art.core.constants.ContextConstants.*; import static ru.art.core.context.Context.*; -import static ru.art.core.wrapper.ExceptionWrapper.*; import static ru.art.logging.LoggingModule.*; @PublicApi @@ -40,27 +40,20 @@ public class AgileConfigurationsActivator { public static Context useAgileConfigurations(String mainModuleId) { ApplicationContextConfiguration configuration = new ApplicationContextConfiguration(mainModuleId, new AgileConfigurationProvider()); Context context = initContext(configuration); - ignoreException(RemoteConfigProvider::useRemoteConfigurations); - loggingModule() - .getLogger(AgileConfigurationsActivator.class) - .info(format(CONFIGURATION_MODE, configModuleState().configurationMode())); + useRemoteConfigurations(); + Logger logger = loggingModule().getLogger(AgileConfigurationsActivator.class); + logger.info(format(CONFIGURATION_MODE, configModuleState().configurationMode())); switch (configModuleState().configurationMode()) { case FILE: String configUrl = configUrl(); if (isEmpty(configUrl)) { - loggingModule() - .getLogger(AgileConfigurationsActivator.class) - .warn(CONFIGURATION_FILE_NOT_EXISTS); + logger.warn(CONFIGURATION_FILE_NOT_EXISTS); return context; } - loggingModule() - .getLogger(AgileConfigurationsActivator.class) - .info(format(CONFIGURATION_FILE_URL, configUrl)); + logger.info(format(CONFIGURATION_FILE_URL, configUrl)); return context; case REMOTE: - loggingModule() - .getLogger(AgileConfigurationsActivator.class) - .info(format(REMOTE_CONFIGURATION_PROPERTIES, configModuleState().remoteConfigProperties())); + logger.info(format(REMOTE_CONFIGURATION_PROPERTIES, configModuleState().remoteConfigProperties())); return context; } return context; diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/http/HttpServerAgileConfiguration.java b/application-config-extensions/src/main/java/ru/art/config/extensions/http/HttpServerAgileConfiguration.java index 8945ada46..d3c829866 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/http/HttpServerAgileConfiguration.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/http/HttpServerAgileConfiguration.java @@ -50,7 +50,7 @@ @Getter public class HttpServerAgileConfiguration extends HttpServerModuleDefaultConfiguration { private final Map contentMappers = configureHttpContentMappers(super.getContentMappers()); - private final Logbook logbook = logbookWithoutResourceLogs(logbookWithoutMetricsLogs()).build(); + private final Logbook logbook = logbookWithoutResourceLogs(logbookWithoutMetricsLogs(this::isEnableValueTracing), this::isEnableValueTracing).build(); private int port; private String path; private int maxThreadsCount; diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolAgileConfiguration.java b/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolAgileConfiguration.java index b5316c343..05328a457 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolAgileConfiguration.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolAgileConfiguration.java @@ -85,6 +85,7 @@ public void refresh() { .username(ifExceptionOrEmpty(() -> config.getString(CONNECTION_SECTION_ID + DOT + USERNAME), DEFAULT_TARANTOOL_USERNAME)) .password(ifExceptionOrEmpty(() -> config.getString(CONNECTION_SECTION_ID + DOT + PASSWORD), EMPTY_STRING)) .operationTimeoutMillis(ifExceptionOrEmpty(() -> config.getInt(CONNECTION_SECTION_ID + DOT + OPERATION_TIMEOUT_MILLIS), DEFAULT_TARANTOOL_OPERATION_TIMEOUT)) + .maxRetryCount(ifExceptionOrEmpty(() -> config.getInt(CONNECTION_SECTION_ID + DOT + MAX_RETRY_COUNT), DEFAULT_TARANTOOL_RETRIES)) .build()) .initialConfiguration(TarantoolInitialConfiguration.builder() .background(nullIfException(() -> config.getBool(INITIAL_SECTION_ID + DOT + BACKGROUND))) diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolConfigKeys.java b/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolConfigKeys.java index 6bfb87ee7..012a48a46 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolConfigKeys.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolConfigKeys.java @@ -38,6 +38,7 @@ public interface TarantoolConfigKeys { String USERNAME = "username"; String PASSWORD = "password"; String OPERATION_TIMEOUT_MILLIS = "operationTimeoutMillis"; + String MAX_RETRY_COUNT = "maxRetryCount"; String BACKGROUND = "background"; String CUSTOM_PROC_TITLE = "customProcTitle"; String MEMTX_DIR = "memtxDir"; diff --git a/application-config-remote-api/src/main/java/ru/art/config/remote/api/specification/RemoteConfigCommunicationSpecification.java b/application-config-remote-api/src/main/java/ru/art/config/remote/api/specification/RemoteConfigCommunicationSpecification.java index e8d7d8ad7..749392ac5 100644 --- a/application-config-remote-api/src/main/java/ru/art/config/remote/api/specification/RemoteConfigCommunicationSpecification.java +++ b/application-config-remote-api/src/main/java/ru/art/config/remote/api/specification/RemoteConfigCommunicationSpecification.java @@ -22,6 +22,7 @@ import ru.art.grpc.client.communicator.GrpcCommunicator.*; import ru.art.grpc.client.specification.*; import ru.art.service.exception.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.config.remote.api.constants.RemoteConfigApiConstants.Methods.*; import static ru.art.config.remote.api.constants.RemoteConfigApiConstants.*; import static ru.art.grpc.client.communicator.GrpcCommunicator.*; @@ -39,7 +40,7 @@ public RemoteConfigCommunicationSpecification(String host, Integer port, String this.path = path; } - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private final GrpcAsynchronousCommunicator applyConfiguration = grpcCommunicator(host, port, path) .serviceId(REMOTE_CONFIG_SERVICE_ID) .methodId(APPLY_CONFIGURATION_METHOD_ID) diff --git a/application-config/src/main/java/ru/art/config/module/ConfigModule.java b/application-config/src/main/java/ru/art/config/module/ConfigModule.java index 756ac3c91..3a6259fa5 100644 --- a/application-config/src/main/java/ru/art/config/module/ConfigModule.java +++ b/application-config/src/main/java/ru/art/config/module/ConfigModule.java @@ -22,15 +22,16 @@ import ru.art.config.configuration.*; import ru.art.config.state.*; import ru.art.core.module.Module; +import static lombok.AccessLevel.PRIVATE; import static ru.art.config.configuration.ConfigModuleConfiguration.*; import static ru.art.config.constants.ConfigModuleConstants.*; import static ru.art.core.context.Context.*; @Getter public class ConfigModule implements Module { - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private static final ConfigModuleConfiguration configModule = context().getModule(CONFIG_MODULE_ID, ConfigModule::new); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private static final ConfigModuleState configModuleState = context().getModuleState(CONFIG_MODULE_ID, ConfigModule::new); private final ConfigModuleConfiguration defaultConfiguration = DEFAULT_CONFIGURATION; private final String id = CONFIG_MODULE_ID; diff --git a/application-configurator-api/src/main/java/ru/art/configurator/api/specification/ConfiguratorCommunicationSpecification.java b/application-configurator-api/src/main/java/ru/art/configurator/api/specification/ConfiguratorCommunicationSpecification.java index e181b0a69..a70595a5f 100644 --- a/application-configurator-api/src/main/java/ru/art/configurator/api/specification/ConfiguratorCommunicationSpecification.java +++ b/application-configurator-api/src/main/java/ru/art/configurator/api/specification/ConfiguratorCommunicationSpecification.java @@ -20,10 +20,12 @@ import lombok.*; import ru.art.configurator.api.model.*; +import ru.art.core.context.*; import ru.art.grpc.client.communicator.*; import ru.art.grpc.client.specification.*; import ru.art.service.exception.*; import static java.lang.System.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.configurator.api.constants.ConfiguratorCommunicationConstants.*; import static ru.art.configurator.api.constants.ConfiguratorServiceConstants.*; import static ru.art.configurator.api.constants.ConfiguratorServiceConstants.Methods.*; @@ -42,13 +44,13 @@ @AllArgsConstructor public class ConfiguratorCommunicationSpecification implements GrpcCommunicationSpecification { private final String host; - private final Integer port; + private final int port; private final String path; private final String serviceId = CONFIGURATOR_COMMUNICATION_SERVICE_ID; private final String profileId = getProperty(PROFILE_PROPERTY); private final ModuleKey moduleKey = new ModuleKey(isEmpty(profileId) ? LOCAL_PROFILE : profileId, contextConfiguration().getMainModuleId()); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private final GrpcCommunicator getProtobufConfig = getProtobufConfig(); private GrpcCommunicator getProtobufConfig() { diff --git a/application-configurator/src/main/java/ru/art/configurator/configuration/ConfiguratorHttpServerConfiguration.java b/application-configurator/src/main/java/ru/art/configurator/configuration/ConfiguratorHttpServerConfiguration.java index 2f3d645ab..a3e1cc98e 100644 --- a/application-configurator/src/main/java/ru/art/configurator/configuration/ConfiguratorHttpServerConfiguration.java +++ b/application-configurator/src/main/java/ru/art/configurator/configuration/ConfiguratorHttpServerConfiguration.java @@ -24,6 +24,7 @@ import ru.art.http.mapper.*; import ru.art.http.server.HttpServerModuleConfiguration.*; import ru.art.http.server.interceptor.*; +import ru.art.http.server.module.*; import static ru.art.config.ConfigProvider.*; import static ru.art.configurator.api.constants.ConfiguratorServiceConstants.*; import static ru.art.configurator.constants.ConfiguratorModuleConstants.*; @@ -39,6 +40,7 @@ import static ru.art.http.server.constants.HttpServerModuleConstants.HttpResourceServiceConstants.HttpResourceType.*; import static ru.art.http.server.interceptor.CookieInterceptor.Error.*; import static ru.art.http.server.interceptor.HttpServerInterceptor.*; +import static ru.art.http.server.module.HttpServerModule.*; import static ru.art.http.server.service.HttpResourceService.*; import static ru.art.metrics.http.filter.MetricsHttpLogFilter.*; import java.util.*; @@ -47,7 +49,7 @@ public class ConfiguratorHttpServerConfiguration extends HttpServerModuleDefaultConfiguration { private final Map contentMappers = configureContentMappers(super.getContentMappers()); private final int port = ifExceptionOrEmpty(() -> config(CONFIGURATOR_SECTION_ID).getInt(CONFIGURATOR_HTTP_PORT_PROPERTY), super.getPort()); - private final Logbook logbook = logbookWithoutMetricsLogs(logbookWithoutResourceLogs()).build(); + private final Logbook logbook = logbookWithoutMetricsLogs(logbookWithoutResourceLogs(this::isEnableValueTracing), this::isEnableRawDataTracing).build(); private final String path = ifExceptionOrEmpty(() -> config(CONFIGURATOR_SECTION_ID).getString(CONFIGURATOR_HTTP_PATH_PROPERTY), CONFIGURATOR_PATH); private final List requestInterceptors = initializeRequestInterceptors(super.getRequestInterceptors()); diff --git a/application-configurator/src/main/java/ru/art/configurator/module/ConfiguratorModule.java b/application-configurator/src/main/java/ru/art/configurator/module/ConfiguratorModule.java index 84aaefc48..789ee0e80 100644 --- a/application-configurator/src/main/java/ru/art/configurator/module/ConfiguratorModule.java +++ b/application-configurator/src/main/java/ru/art/configurator/module/ConfiguratorModule.java @@ -31,7 +31,7 @@ import ru.art.grpc.server.state.*; import ru.art.http.client.configuration.*; import ru.art.http.client.module.*; -import ru.art.http.client.state.HttpClientModuleState; +import ru.art.http.client.state.*; import ru.art.http.server.*; import ru.art.http.server.module.*; import ru.art.http.server.specification.*; @@ -45,6 +45,7 @@ import ru.art.rocks.db.state.*; import ru.art.service.*; import static java.util.UUID.*; +import static lombok.AccessLevel.*; import static ru.art.config.ConfigProvider.*; import static ru.art.configurator.api.constants.ConfiguratorServiceConstants.*; import static ru.art.configurator.constants.ConfiguratorModuleConstants.*; @@ -61,7 +62,7 @@ @Getter public class ConfiguratorModule implements Module { - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private static final ConfiguratorModuleConfiguration configuratorModule = context().getModule(CONFIGURATOR_MODULE_ID, ConfiguratorModule::new); private final String id = CONFIGURATOR_MODULE_ID; private final ConfiguratorModuleConfiguration defaultConfiguration = new ConfiguratorModuleConfiguration(); diff --git a/application-core/src/main/java/ru/art/core/constants/ContextState.java b/application-core/src/main/java/ru/art/core/constants/ContextState.java index 3c5efcf7b..83bf75d5d 100644 --- a/application-core/src/main/java/ru/art/core/constants/ContextState.java +++ b/application-core/src/main/java/ru/art/core/constants/ContextState.java @@ -22,6 +22,5 @@ public enum ContextState { REFRESHING_MODULES, REFRESHING_AND_RELOADING_MODULES, READY, - UNLOADING_MODULES, EMPTY, } diff --git a/application-core/src/main/java/ru/art/core/context/Context.java b/application-core/src/main/java/ru/art/core/context/Context.java index dd5b74f3b..59431bf23 100644 --- a/application-core/src/main/java/ru/art/core/context/Context.java +++ b/application-core/src/main/java/ru/art/core/context/Context.java @@ -44,10 +44,10 @@ public class Context { private static final ReentrantLock LOCK = new ReentrantLock(); private static volatile Context INSTANCE; - private Map> modules = mapOf(); - private ContextInitialConfiguration initialConfiguration = new ContextInitialDefaultConfiguration(); - private ContextState state = READY; - private Long lastActionTimestamp = currentTimeMillis(); + private volatile ContextInitialConfiguration initialConfiguration = new ContextInitialDefaultConfiguration(); + private volatile ContextState state = READY; + private volatile Long lastActionTimestamp = currentTimeMillis(); + private Map> modules = concurrentHashMap(); private Context() { if (initialConfiguration.isUnloadModulesOnShutdown()) { @@ -116,6 +116,9 @@ public static ContextInitialConfiguration contextConfiguration() { public C getModule(String moduleId, Module toLoadIfNotExists) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); + if (state != READY) { + return toLoadIfNotExists.getDefaultConfiguration(); + } ModuleContainer moduleContainer = modules.get(moduleId); PreconfiguredModuleProvider preconfiguredModulesProvider; if (nonNull(moduleContainer)) { @@ -131,6 +134,9 @@ public C getModule(String public S getModuleState(String moduleId, Module toLoadIfNotExists) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); + if (state == LOADING_MODULES) { + return toLoadIfNotExists.getState(); + } ModuleContainer moduleContainer = modules.get(moduleId); PreconfiguredModuleProvider preconfiguredModulesProvider; if (nonNull(moduleContainer)) { @@ -146,6 +152,9 @@ public S getModuleState(S public C getModule(String moduleId, Supplier> toLoadIfNotExists) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); + if (state != READY) { + return toLoadIfNotExists.get().getDefaultConfiguration(); + } ModuleContainer moduleContainer = modules.get(moduleId); PreconfiguredModuleProvider preconfiguredModulesProvider; if (nonNull(moduleContainer)) { @@ -162,6 +171,9 @@ public C getModule(String public S getModuleState(String moduleId, Supplier> toLoadIfNotExists) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); + if (state == LOADING_MODULES) { + return toLoadIfNotExists.get().getState(); + } ModuleContainer moduleContainer = modules.get(moduleId); PreconfiguredModuleProvider preconfiguredModulesProvider; if (nonNull(moduleContainer)) { @@ -178,10 +190,11 @@ public S getModuleState(S public Context loadModule(Module module) { if (isNull(module)) throw new ContextInitializationException(MODULE_ID_IS_NULL); + ContextState currentState = state; state = LOADING_MODULES; modules.put(module.getId(), new ModuleContainer<>(module, cast(module.getDefaultConfiguration()))); out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp)); - state = READY; + state = currentState; module.onLoad(); lastActionTimestamp = currentTimeMillis(); return this; @@ -189,10 +202,11 @@ public Context loadModule public Context loadModule(Module module, ModuleConfigurator moduleConfigurator) { if (isNull(module)) throw new ContextInitializationException(MODULE_ID_IS_NULL); + ContextState currentState = state; state = LOADING_MODULES; modules.put(module.getId(), new ModuleContainer<>(module, cast(moduleConfigurator.configure(module)))); out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp)); - state = READY; + state = currentState; module.onLoad(); lastActionTimestamp = currentTimeMillis(); return this; @@ -200,9 +214,10 @@ public Context loadModule public Context loadModule(Module module, C customModuleConfiguration) { if (isNull(module)) throw new ContextInitializationException(MODULE_ID_IS_NULL); + ContextState currentState = state; state = LOADING_MODULES; modules.put(module.getId(), new ModuleContainer<>(module, cast(nonNull(customModuleConfiguration) ? customModuleConfiguration : module.getDefaultConfiguration()))); - state = READY; + state = currentState; module.onLoad(); out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp)); lastActionTimestamp = currentTimeMillis(); @@ -210,10 +225,11 @@ public Context loadModule } private C loadModule(Module module, PreconfiguredModuleProvider preconfiguredModulesProvider) { + ContextState currentState = state; state = LOADING_MODULES; C configuration = cast(preconfiguredModulesProvider.getModuleConfiguration(module.getId()).orElse(module.getDefaultConfiguration())); + state = currentState; loadModule(module, configuration); - state = READY; return cast(configuration); } @@ -225,11 +241,12 @@ public Context overrideModule(String moduleId, C } ModuleContainer moduleContainer = modules.get(moduleId); if (isNull(moduleContainer)) return this; + ContextState currentState = state; state = LOADING_MODULES; modules.put(moduleId, moduleContainer.overrideConfiguration(cast(customModuleConfiguration))); out.println(format(MODULE_OVERRIDDEN_MESSAGE, moduleId, currentTimeMillis() - lastActionTimestamp)); lastActionTimestamp = currentTimeMillis(); - state = READY; + state = currentState; return this; } @@ -238,11 +255,12 @@ public Context reloadModule(String moduleId) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); ModuleContainer moduleContainer = modules.get(moduleId); if (isNull(moduleContainer)) return this; + ContextState currentState = state; state = RELOADING_MODULES; moduleContainer.reloadModule(); out.println(format(MODULE_RELOADED_MESSAGE, moduleId, currentTimeMillis() - lastActionTimestamp)); lastActionTimestamp = currentTimeMillis(); - state = READY; + state = currentState; return this; } @@ -251,16 +269,18 @@ public Context refreshModule(String moduleId) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); ModuleContainer moduleContainer = modules.get(moduleId); if (isNull(moduleContainer)) return this; + ContextState currentState = state; state = REFRESHING_MODULES; moduleContainer.refreshConfiguration(); out.println(format(MODULE_REFRESHED_MESSAGE, moduleId, currentTimeMillis() - lastActionTimestamp)); lastActionTimestamp = currentTimeMillis(); - state = READY; + state = currentState; return this; } public Context refreshAndReloadModule(String moduleId) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); + ContextState currentState = state; state = REFRESHING_AND_RELOADING_MODULES; ModuleContainer moduleContainer = modules.get(moduleId); if (isNull(moduleContainer)) return this; @@ -268,7 +288,7 @@ public Context refreshAndReloadModule(String moduleId) { moduleContainer.refreshConfiguration(); out.println(format(MODULE_REFRESHED_AND_RELOADED_MESSAGE, moduleId, currentTimeMillis() - lastActionTimestamp)); lastActionTimestamp = currentTimeMillis(); - state = READY; + state = currentState; return this; } @@ -308,7 +328,6 @@ public static boolean contextIsNotReady() { } private void unloadModules() { - state = UNLOADING_MODULES; modules.values().forEach(module -> module.getModule().onUnload()); modules.clear(); } diff --git a/application-entity/src/main/java/ru/art/entity/CollectionValue.java b/application-entity/src/main/java/ru/art/entity/CollectionValue.java index 3fab8dc37..ba2cde230 100644 --- a/application-entity/src/main/java/ru/art/entity/CollectionValue.java +++ b/application-entity/src/main/java/ru/art/entity/CollectionValue.java @@ -339,7 +339,7 @@ public List getLongList() { } return list; } - return cast(elements); + return cast(fixedArrayOf(elements)); } case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { @@ -529,7 +529,10 @@ public List getIntList() { } return list; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).intValue()) + .collect(toList()); } case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { @@ -616,7 +619,10 @@ public List getByteList() { } return list; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).byteValue()) + .collect(toList()); } } throw new ValueMappingException(format(REQUEST_LIST_ELEMENTS_TYPE_INVALID, BYTE.toString(), elementsType.toString())); @@ -655,7 +661,10 @@ public List getDoubleList() { } return list; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).doubleValue()) + .collect(toList()); } case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { @@ -742,7 +751,10 @@ public List getFloatList() { } return list; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).floatValue()) + .collect(toList()); } case INT: { if (collectionMode == PRIMITIVE_ARRAY) { @@ -775,7 +787,7 @@ public List getFloatList() { public Set getValueSet() { if (isEmpty()) return emptySet(); - Set Set = setOf(); + Set set = setOf(); switch (elementsType) { case STRING: return elements @@ -786,9 +798,9 @@ public Set getValueSet() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Set.add(longPrimitive(element)); + set.add(longPrimitive(element)); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -798,9 +810,9 @@ public Set getValueSet() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Set.add(doublePrimitive(element)); + set.add(doublePrimitive(element)); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -810,9 +822,9 @@ public Set getValueSet() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Set.add(floatPrimitive(element)); + set.add(floatPrimitive(element)); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -822,9 +834,9 @@ public Set getValueSet() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Set.add(intPrimitive(element)); + set.add(intPrimitive(element)); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -834,9 +846,9 @@ public Set getValueSet() { case BOOL: { if (collectionMode == PRIMITIVE_ARRAY) { for (boolean element : boolElements) { - Set.add(boolPrimitive(element)); + set.add(boolPrimitive(element)); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -846,9 +858,9 @@ public Set getValueSet() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Set.add(bytePrimitive(element)); + set.add(bytePrimitive(element)); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -903,7 +915,7 @@ public Set getEntitySet() { public Set getLongSet() { if (isEmpty()) return emptySet(); - Set Set = setOf(); + Set set = setOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -918,18 +930,21 @@ public Set getLongSet() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Set.add(element); + set.add(element); } - return Set; + return set; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).longValue()) + .collect(toSet()); } case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Set.add((long) element); + set.add((long) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -939,9 +954,9 @@ public Set getLongSet() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Set.add((long) element); + set.add((long) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -951,9 +966,9 @@ public Set getLongSet() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Set.add((long) element); + set.add((long) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -963,9 +978,9 @@ public Set getLongSet() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Set.add((long) element); + set.add((long) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -978,44 +993,44 @@ public Set getLongSet() { public Set getStringSet() { if (isEmpty()) return emptySet(); - Set Set = setOf(); + Set set = setOf(); if (collectionMode == PRIMITIVE_ARRAY) { switch (elementsType) { case LONG: { for (long element : longElements) { - Set.add(EMPTY_STRING + element); + set.add(EMPTY_STRING + element); } - return Set; + return set; } case DOUBLE: { for (double element : doubleElements) { - Set.add(EMPTY_STRING + element); + set.add(EMPTY_STRING + element); } - return Set; + return set; } case FLOAT: { for (float element : floatElements) { - Set.add(EMPTY_STRING + element); + set.add(EMPTY_STRING + element); } - return Set; + return set; } case INT: { for (int element : intElements) { - Set.add(EMPTY_STRING + element); + set.add(EMPTY_STRING + element); } - return Set; + return set; } case BOOL: { for (boolean element : boolElements) { - Set.add(EMPTY_STRING + element); + set.add(EMPTY_STRING + element); } - return Set; + return set; } case BYTE: { for (byte element : byteElements) { - Set.add(EMPTY_STRING + element); + set.add(EMPTY_STRING + element); } - return Set; + return set; } } } @@ -1031,11 +1046,11 @@ public Set getBoolSet() { if (elementsType != BOOL) { throw new ValueMappingException(format(REQUEST_SET_ELEMENTS_TYPE_INVALID, BOOL.toString(), elementsType.toString())); } - Set Set = setOf(); + Set set = setOf(); for (boolean element : boolElements) { - Set.add(element); + set.add(element); } - return Set; + return set; } switch (elementsType) { case VALUE: @@ -1057,7 +1072,7 @@ public Set getBoolSet() { public Set getIntSet() { if (isEmpty()) return emptySet(); - Set Set = setOf(); + Set set = setOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1072,9 +1087,9 @@ public Set getIntSet() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Set.add((int) element); + set.add((int) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1084,9 +1099,9 @@ public Set getIntSet() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Set.add((int) element); + set.add((int) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1096,9 +1111,9 @@ public Set getIntSet() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Set.add((int) element); + set.add((int) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1108,18 +1123,21 @@ public Set getIntSet() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Set.add(element); + set.add(element); } - return Set; + return set; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).intValue()) + .collect(toSet()); } case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Set.add((int) element); + set.add((int) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1132,7 +1150,7 @@ public Set getIntSet() { public Set getByteSet() { if (isEmpty()) return emptySet(); - Set Set = setOf(); + Set set = setOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1147,9 +1165,9 @@ public Set getByteSet() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Set.add((byte) element); + set.add((byte) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1159,9 +1177,9 @@ public Set getByteSet() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Set.add((byte) element); + set.add((byte) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1171,9 +1189,9 @@ public Set getByteSet() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Set.add((byte) element); + set.add((byte) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1183,9 +1201,9 @@ public Set getByteSet() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Set.add((byte) element); + set.add((byte) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1195,11 +1213,14 @@ public Set getByteSet() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Set.add(element); + set.add(element); } - return Set; + return set; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).byteValue()) + .collect(toSet()); } } throw new ValueMappingException(format(REQUEST_SET_ELEMENTS_TYPE_INVALID, BYTE.toString(), elementsType.toString())); @@ -1207,7 +1228,7 @@ public Set getByteSet() { public Set getDoubleSet() { if (isEmpty()) return emptySet(); - Set Set = setOf(); + Set set = setOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1222,9 +1243,9 @@ public Set getDoubleSet() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Set.add((double) element); + set.add((double) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1234,18 +1255,21 @@ public Set getDoubleSet() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Set.add(element); + set.add(element); } - return Set; + return set; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).doubleValue()) + .collect(toSet()); } case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Set.add((double) element); + set.add((double) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1255,9 +1279,9 @@ public Set getDoubleSet() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Set.add((double) element); + set.add((double) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1267,9 +1291,9 @@ public Set getDoubleSet() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Set.add((double) element); + set.add((double) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1282,7 +1306,7 @@ public Set getDoubleSet() { public Set getFloatSet() { if (isEmpty()) return emptySet(); - Set Set = setOf(); + Set set = setOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1297,9 +1321,9 @@ public Set getFloatSet() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Set.add((float) element); + set.add((float) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1309,9 +1333,9 @@ public Set getFloatSet() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Set.add((float) element); + set.add((float) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1321,18 +1345,21 @@ public Set getFloatSet() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Set.add(element); + set.add(element); } - return Set; + return set; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).floatValue()) + .collect(toSet()); } case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Set.add((float) element); + set.add((float) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1342,9 +1369,9 @@ public Set getFloatSet() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Set.add((float) element); + set.add((float) element); } - return Set; + return set; } return elements.stream() .filter(Objects::nonNull) @@ -1358,7 +1385,7 @@ public Set getFloatSet() { public Queue getValueQueue() { if (isEmpty()) return queueOf(); - Queue Queue = queueOf(); + Queue queue = queueOf(); switch (elementsType) { case STRING: return elements @@ -1369,9 +1396,9 @@ public Queue getValueQueue() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Queue.add(longPrimitive(element)); + queue.add(longPrimitive(element)); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1381,9 +1408,9 @@ public Queue getValueQueue() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Queue.add(doublePrimitive(element)); + queue.add(doublePrimitive(element)); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1393,9 +1420,9 @@ public Queue getValueQueue() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Queue.add(floatPrimitive(element)); + queue.add(floatPrimitive(element)); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1405,9 +1432,9 @@ public Queue getValueQueue() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Queue.add(intPrimitive(element)); + queue.add(intPrimitive(element)); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1417,9 +1444,9 @@ public Queue getValueQueue() { case BOOL: { if (collectionMode == PRIMITIVE_ARRAY) { for (boolean element : boolElements) { - Queue.add(boolPrimitive(element)); + queue.add(boolPrimitive(element)); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1429,9 +1456,9 @@ public Queue getValueQueue() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Queue.add(bytePrimitive(element)); + queue.add(bytePrimitive(element)); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1486,7 +1513,7 @@ public Queue getEntityQueue() { public Queue getLongQueue() { if (isEmpty()) return queueOf(); - Queue Queue = queueOf(); + Queue queue = queueOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1501,18 +1528,21 @@ public Queue getLongQueue() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Queue.add(element); + queue.add(element); } - return Queue; + return queue; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).longValue()) + .collect(toCollection(CollectionsFactory::queueOf)); } case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Queue.add((long) element); + queue.add((long) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1522,9 +1552,9 @@ public Queue getLongQueue() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Queue.add((long) element); + queue.add((long) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1534,9 +1564,9 @@ public Queue getLongQueue() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Queue.add((long) element); + queue.add((long) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1546,9 +1576,9 @@ public Queue getLongQueue() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Queue.add((long) element); + queue.add((long) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1561,44 +1591,44 @@ public Queue getLongQueue() { public Queue getStringQueue() { if (isEmpty()) return queueOf(); - Queue Queue = queueOf(); + Queue queue = queueOf(); if (collectionMode == PRIMITIVE_ARRAY) { switch (elementsType) { case LONG: { for (long element : longElements) { - Queue.add(EMPTY_STRING + element); + queue.add(EMPTY_STRING + element); } - return Queue; + return queue; } case DOUBLE: { for (double element : doubleElements) { - Queue.add(EMPTY_STRING + element); + queue.add(EMPTY_STRING + element); } - return Queue; + return queue; } case FLOAT: { for (float element : floatElements) { - Queue.add(EMPTY_STRING + element); + queue.add(EMPTY_STRING + element); } - return Queue; + return queue; } case INT: { for (int element : intElements) { - Queue.add(EMPTY_STRING + element); + queue.add(EMPTY_STRING + element); } - return Queue; + return queue; } case BOOL: { for (boolean element : boolElements) { - Queue.add(EMPTY_STRING + element); + queue.add(EMPTY_STRING + element); } - return Queue; + return queue; } case BYTE: { for (byte element : byteElements) { - Queue.add(EMPTY_STRING + element); + queue.add(EMPTY_STRING + element); } - return Queue; + return queue; } } } @@ -1614,11 +1644,11 @@ public Queue getBoolQueue() { if (elementsType != BOOL) { throw new ValueMappingException(format(REQUEST_QUEUE_ELEMENTS_TYPE_INVALID, BOOL.toString(), elementsType.toString())); } - Queue Queue = queueOf(); + Queue queue = queueOf(); for (boolean element : boolElements) { - Queue.add(element); + queue.add(element); } - return Queue; + return queue; } switch (elementsType) { case VALUE: @@ -1640,7 +1670,7 @@ public Queue getBoolQueue() { public Queue getIntQueue() { if (isEmpty()) return queueOf(); - Queue Queue = queueOf(); + Queue queue = queueOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1655,9 +1685,9 @@ public Queue getIntQueue() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Queue.add((int) element); + queue.add((int) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1667,9 +1697,9 @@ public Queue getIntQueue() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Queue.add((int) element); + queue.add((int) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1679,9 +1709,9 @@ public Queue getIntQueue() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Queue.add((int) element); + queue.add((int) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1691,18 +1721,21 @@ public Queue getIntQueue() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Queue.add(element); + queue.add(element); } - return Queue; + return queue; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).intValue()) + .collect(toCollection(CollectionsFactory::queueOf)); } case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Queue.add((int) element); + queue.add((int) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1715,7 +1748,7 @@ public Queue getIntQueue() { public Queue getByteQueue() { if (isEmpty()) return queueOf(); - Queue Queue = queueOf(); + Queue queue = queueOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1730,9 +1763,9 @@ public Queue getByteQueue() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Queue.add((byte) element); + queue.add((byte) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1742,9 +1775,9 @@ public Queue getByteQueue() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Queue.add((byte) element); + queue.add((byte) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1754,9 +1787,9 @@ public Queue getByteQueue() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Queue.add((byte) element); + queue.add((byte) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1766,9 +1799,9 @@ public Queue getByteQueue() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Queue.add((byte) element); + queue.add((byte) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1778,11 +1811,14 @@ public Queue getByteQueue() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Queue.add(element); + queue.add(element); } - return Queue; + return queue; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).byteValue()) + .collect(toCollection(CollectionsFactory::queueOf)); } } throw new ValueMappingException(format(REQUEST_QUEUE_ELEMENTS_TYPE_INVALID, BYTE.toString(), elementsType.toString())); @@ -1790,7 +1826,7 @@ public Queue getByteQueue() { public Queue getDoubleQueue() { if (isEmpty()) return queueOf(); - Queue Queue = queueOf(); + Queue queue = queueOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1805,9 +1841,9 @@ public Queue getDoubleQueue() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Queue.add((double) element); + queue.add((double) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1817,18 +1853,21 @@ public Queue getDoubleQueue() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Queue.add(element); + queue.add(element); } - return Queue; + return queue; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).doubleValue()) + .collect(toCollection(CollectionsFactory::queueOf)); } case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Queue.add((double) element); + queue.add((double) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1838,9 +1877,9 @@ public Queue getDoubleQueue() { case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Queue.add((double) element); + queue.add((double) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1850,9 +1889,9 @@ public Queue getDoubleQueue() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Queue.add((double) element); + queue.add((double) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1865,7 +1904,7 @@ public Queue getDoubleQueue() { public Queue getFloatQueue() { if (isEmpty()) return queueOf(); - Queue Queue = queueOf(); + Queue queue = queueOf(); switch (elementsType) { case VALUE: return elements.stream() @@ -1880,9 +1919,9 @@ public Queue getFloatQueue() { case LONG: { if (collectionMode == PRIMITIVE_ARRAY) { for (long element : longElements) { - Queue.add((float) element); + queue.add((float) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1892,9 +1931,9 @@ public Queue getFloatQueue() { case DOUBLE: { if (collectionMode == PRIMITIVE_ARRAY) { for (double element : doubleElements) { - Queue.add((float) element); + queue.add((float) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1904,18 +1943,21 @@ public Queue getFloatQueue() { case FLOAT: { if (collectionMode == PRIMITIVE_ARRAY) { for (float element : floatElements) { - Queue.add(element); + queue.add(element); } - return Queue; + return queue; } - return cast(elements); + return elements.stream() + .filter(Objects::nonNull) + .map(element -> ((Number) element).floatValue()) + .collect(toCollection(CollectionsFactory::queueOf)); } case INT: { if (collectionMode == PRIMITIVE_ARRAY) { for (int element : intElements) { - Queue.add((float) element); + queue.add((float) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) @@ -1925,9 +1967,9 @@ public Queue getFloatQueue() { case BYTE: { if (collectionMode == PRIMITIVE_ARRAY) { for (byte element : byteElements) { - Queue.add((float) element); + queue.add((float) element); } - return Queue; + return queue; } return elements.stream() .filter(Objects::nonNull) diff --git a/application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorChannelFactory.java b/application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorChannelFactory.java index 3348a3427..538d1ba53 100644 --- a/application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorChannelFactory.java +++ b/application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorChannelFactory.java @@ -1,9 +1,9 @@ package ru.art.grpc.client.communicator; import io.grpc.*; -import ru.art.grpc.client.module.*; import static io.grpc.ManagedChannelBuilder.*; import static java.util.concurrent.TimeUnit.*; +import static ru.art.core.context.Context.*; import static ru.art.grpc.client.module.GrpcClientModule.*; public class GrpcCommunicatorChannelFactory { @@ -12,10 +12,11 @@ static ManagedChannel createChannel(GrpcCommunicationConfiguration configuration if (configuration.isUseSecuredTransport()) { channelBuilder.useTransportSecurity(); } - return grpcClientModuleState().registerChannel(channelBuilder + ManagedChannel channel = channelBuilder .keepAliveTime(configuration.getKeepAliveTimeNanos(), NANOSECONDS) .keepAliveTimeout(configuration.getKeepAliveTimeOutNanos(), NANOSECONDS) .keepAliveWithoutCalls(configuration.isKeepAliveWithoutCalls()) - .build()); + .build(); + return grpcClientModuleState().registerChannel(channel); } } diff --git a/application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorImplementation.java b/application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorImplementation.java index 99bac2314..1cb2b43d7 100644 --- a/application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorImplementation.java +++ b/application-grpc-client/src/main/java/ru/art/grpc/client/communicator/GrpcCommunicatorImplementation.java @@ -19,10 +19,13 @@ package ru.art.grpc.client.communicator; import io.grpc.*; +import lombok.*; +import org.apache.logging.log4j.*; import ru.art.core.lazy.*; import ru.art.core.runnable.*; import ru.art.core.validator.*; import ru.art.entity.*; +import ru.art.entity.Value; import ru.art.entity.interceptor.*; import ru.art.entity.mapper.*; import ru.art.grpc.client.handler.*; @@ -30,6 +33,7 @@ import ru.art.service.model.*; import static java.util.Objects.*; import static java.util.concurrent.TimeUnit.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.caster.Caster.*; import static ru.art.core.checker.CheckerForEmptiness.*; import static ru.art.core.constants.StringConstants.*; @@ -44,6 +48,8 @@ public class GrpcCommunicatorImplementation implements GrpcCommunicator, GrpcCom private final GrpcCommunicationConfiguration configuration = new GrpcCommunicationConfiguration(); private final BuilderValidator validator = new BuilderValidator(GrpcCommunicator.class.getName()); private final LazyLoadingValue channel = lazyValue(() -> createChannel(configuration)); + @Getter(lazy = true, value = PRIVATE) + private static final Logger logger = loggingModule().getLogger(GrpcCommunicator.class); GrpcCommunicatorImplementation(String host, int port, String path) { configuration.setUrl(validator.notEmptyField(host, "host") + COLON + validator.notNullField(port, "port")); @@ -69,7 +75,9 @@ public class GrpcCommunicatorImplementation implements GrpcCommunicator, GrpcCom configuration.setUrl(targetConfiguration.url()); return; } - configuration.setUrl(validator.notEmptyField(targetConfiguration.host(), "host") + COLON + validator.notNullField(targetConfiguration.port(), "port")); + configuration.setUrl(validator.notEmptyField(targetConfiguration.host(), "host") + + COLON + + validator.notNullField(targetConfiguration.port(), "port")); } @Override @@ -140,9 +148,8 @@ public void shutdownChannel() { return; } ignoreException((ExceptionRunnable) () -> channel - .shutdownNow() - .awaitTermination(GRPC_CHANNEL_SHUTDOWN_TIMEOUT, MILLISECONDS), - loggingModule().getLogger(GrpcCommunicator.class)::error); + .shutdownNow() + .awaitTermination(GRPC_CHANNEL_SHUTDOWN_TIMEOUT, MILLISECONDS), getLogger()::error); } @Override diff --git a/application-grpc-client/src/main/java/ru/art/grpc/client/configuration/GrpcClientModuleConfiguration.java b/application-grpc-client/src/main/java/ru/art/grpc/client/configuration/GrpcClientModuleConfiguration.java index 1895b217c..50587dbbd 100644 --- a/application-grpc-client/src/main/java/ru/art/grpc/client/configuration/GrpcClientModuleConfiguration.java +++ b/application-grpc-client/src/main/java/ru/art/grpc/client/configuration/GrpcClientModuleConfiguration.java @@ -101,15 +101,11 @@ class GrpcClientModuleDefaultConfiguration implements GrpcClientModuleConfigurat private boolean waitForReady = false; private List initializeInterceptors() { - List interceptors = linkedListOf(new GrpcClientTracingInterceptor()); - if (isEnableRawDataTracing()) { - interceptors.add(new GrpcClientLoggingInterceptor()); - } - return interceptors; + return linkedListOf(new GrpcClientTracingInterceptor(), new GrpcClientLoggingInterceptor()); } private List> initializeValueInterceptors() { - return isEnableValueTracing() ? linkedListOf(new LoggingValueInterceptor<>()) : linkedListOf(); + return linkedListOf(new LoggingValueInterceptor<>(this::isEnableValueTracing)); } } } diff --git a/application-grpc-client/src/main/java/ru/art/grpc/client/interceptor/GrpcClientLoggingInterceptor.java b/application-grpc-client/src/main/java/ru/art/grpc/client/interceptor/GrpcClientLoggingInterceptor.java index 275cc0812..ef708af57 100644 --- a/application-grpc-client/src/main/java/ru/art/grpc/client/interceptor/GrpcClientLoggingInterceptor.java +++ b/application-grpc-client/src/main/java/ru/art/grpc/client/interceptor/GrpcClientLoggingInterceptor.java @@ -19,35 +19,41 @@ package ru.art.grpc.client.interceptor; import io.grpc.*; +import lombok.*; import org.apache.logging.log4j.*; import static java.text.MessageFormat.*; +import static lombok.AccessLevel.*; import static ru.art.grpc.client.constants.GrpcClientModuleConstants.*; +import static ru.art.grpc.client.module.GrpcClientModule.*; import static ru.art.logging.LoggingModule.*; import javax.annotation.*; +import java.util.function.*; public class GrpcClientLoggingInterceptor implements ClientInterceptor { - - private final Logger logger = loggingModule() - .getLogger(GrpcClientLoggingInterceptor.class); + @Getter(lazy = true, value = PRIVATE) + private final static Logger logger = loggingModule().getLogger(GrpcClientLoggingInterceptor.class); @Override public ClientCall interceptCall(MethodDescriptor methodDescriptor, CallOptions callOptions, Channel channel) { + if (!grpcClientModule().isEnableRawDataTracing()) { + return channel.newCall(methodDescriptor, callOptions); + } return new ForwardingClientCall.SimpleForwardingClientCall(channel.newCall(methodDescriptor, callOptions)) { @Override public void sendMessage(ReqT message) { - logger.info(format(GRPC_ON_REQUEST_MESSAGE, message)); + getLogger().info(format(GRPC_ON_REQUEST_MESSAGE, message)); super.sendMessage(message); } @Override public void cancel(@Nullable String message, @Nullable Throwable cause) { - logger.error(format(GRPC_ON_CANCEL, message, cause)); + getLogger().error(format(GRPC_ON_CANCEL, message, cause)); super.cancel(message, cause); } @Override public void halfClose() { - logger.info(GRPC_ON_HALF_CLOSE); + getLogger().info(GRPC_ON_HALF_CLOSE); super.halfClose(); } @@ -56,25 +62,25 @@ public void start(Listener responseListener, Metadata headers) { super.start(new Listener() { @Override public void onHeaders(Metadata headers) { - logger.info(format(GRPC_ON_RESPONSE_HEADERS, headers.toString())); + getLogger().info(format(GRPC_ON_RESPONSE_HEADERS, headers.toString())); responseListener.onHeaders(headers); } @Override public void onMessage(RespT message) { - logger.info(format(GRPC_ON_RESPONSE_MESSAGE, message)); + getLogger().info(format(GRPC_ON_RESPONSE_MESSAGE, message)); responseListener.onMessage(message); } @Override public void onClose(Status status, Metadata trailers) { - logger.info(format(GRPC_ON_CLOSE, status.toString(), trailers.toString())); + getLogger().info(format(GRPC_ON_CLOSE, status.toString(), trailers.toString())); responseListener.onClose(status, trailers); } @Override public void onReady() { - logger.info(GRPC_ON_READY); + getLogger().info(GRPC_ON_READY); responseListener.onReady(); } }, headers); diff --git a/application-grpc-client/src/main/java/ru/art/grpc/client/module/GrpcClientModule.java b/application-grpc-client/src/main/java/ru/art/grpc/client/module/GrpcClientModule.java index c99222e9d..1a235fd0f 100644 --- a/application-grpc-client/src/main/java/ru/art/grpc/client/module/GrpcClientModule.java +++ b/application-grpc-client/src/main/java/ru/art/grpc/client/module/GrpcClientModule.java @@ -45,7 +45,8 @@ public class GrpcClientModule implements Module> initializeValueInterceptors() { - return isEnableValueTracing() ? linkedListOf(new LoggingValueInterceptor<>()) : linkedListOf(); + return linkedListOf(new LoggingValueInterceptor<>(this::isEnableValueTracing)); } private List initializeInterceptors() { diff --git a/application-grpc-server/src/main/java/ru/art/grpc/server/interceptor/GrpcServerLoggingInterceptor.java b/application-grpc-server/src/main/java/ru/art/grpc/server/interceptor/GrpcServerLoggingInterceptor.java index 4e3e487b0..cae0c434d 100644 --- a/application-grpc-server/src/main/java/ru/art/grpc/server/interceptor/GrpcServerLoggingInterceptor.java +++ b/application-grpc-server/src/main/java/ru/art/grpc/server/interceptor/GrpcServerLoggingInterceptor.java @@ -22,6 +22,7 @@ import io.grpc.ForwardingServerCallListener.*; import io.grpc.*; import io.grpc.ServerCall.*; +import lombok.*; import org.apache.logging.log4j.Logger; import ru.art.grpc.server.module.GrpcServerModule; import ru.art.logging.*; @@ -30,6 +31,7 @@ import static java.lang.System.*; import static java.text.MessageFormat.*; import static java.util.UUID.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.checker.CheckerForEmptiness.*; import static ru.art.core.extension.StringExtensions.*; import static ru.art.grpc.server.constants.GrpcServerLoggingMessages.*; @@ -39,7 +41,8 @@ import static ru.art.logging.LoggingParametersManager.*; public class GrpcServerLoggingInterceptor implements ServerInterceptor { - private final Logger logger = loggingModule().getLogger(GrpcServerLoggingInterceptor.class); + @Getter(lazy = true, value = PRIVATE) + private static final Logger logger = loggingModule().getLogger(GrpcServerLoggingInterceptor.class); @Override public Listener interceptCall(ServerCall serverCall, Metadata metadata, ServerCallHandler serverCallHandler) { @@ -56,53 +59,53 @@ public Listener interceptCall(ServerCall server if (!grpcServerModule().isEnableRawDataTracing()) { return serverCallHandler.startCall(serverCall, metadata); } - logger.info(format(GRPC_ON_REQUEST_HEADERS, emptyIfNull(metadata.toString()))); + getLogger().info(format(GRPC_ON_REQUEST_HEADERS, emptyIfNull(metadata.toString()))); return new SimpleForwardingServerCallListener(serverCallHandler.startCall(new SimpleForwardingServerCall(serverCall) { @Override public void sendMessage(RespT message) { - logger.info(format(GRPC_ON_RESPONSE_MESSAGE, emptyIfNull(message))); + getLogger().info(format(GRPC_ON_RESPONSE_MESSAGE, emptyIfNull(message))); super.sendMessage(message); } @Override public void sendHeaders(Metadata headers) { - logger.info(format(GRPC_ON_RESPONSE_HEADERS, emptyIfNull(metadata.toString()))); + getLogger().info(format(GRPC_ON_RESPONSE_HEADERS, emptyIfNull(metadata.toString()))); super.sendHeaders(headers); } @Override public void close(Status status, Metadata trailers) { - logger.info(format(GRPC_ON_CLOSE, emptyIfNull(metadata.toString()))); + getLogger().info(format(GRPC_ON_CLOSE, emptyIfNull(metadata.toString()))); super.close(status, trailers); } }, metadata)) { @Override public void onMessage(ReqT message) { - logger.info(format(GRPC_ON_REQUEST_MESSAGE, emptyIfNull(message))); + getLogger().info(format(GRPC_ON_REQUEST_MESSAGE, emptyIfNull(message))); super.onMessage(message); } @Override public void onHalfClose() { - logger.info(GRPC_ON_HALF_CLOSE); + getLogger().info(GRPC_ON_HALF_CLOSE); super.onHalfClose(); } @Override public void onCancel() { - logger.info(GRPC_ON_CANCEL); + getLogger().info(GRPC_ON_CANCEL); super.onCancel(); } @Override public void onComplete() { - logger.info(GRPC_ON_COMPLETE); + getLogger().info(GRPC_ON_COMPLETE); super.onComplete(); } @Override public void onReady() { - logger.info(GRPC_ON_READY); + getLogger().info(GRPC_ON_READY); super.onReady(); } }; diff --git a/application-http-client/src/main/java/ru/art/http/client/communicator/HttpCommunicationExecutor.java b/application-http-client/src/main/java/ru/art/http/client/communicator/HttpCommunicationExecutor.java index c58f15897..fa8c6795d 100644 --- a/application-http-client/src/main/java/ru/art/http/client/communicator/HttpCommunicationExecutor.java +++ b/application-http-client/src/main/java/ru/art/http/client/communicator/HttpCommunicationExecutor.java @@ -101,7 +101,7 @@ private static ResponseType executeHttpUriRequest(HttpCommunicati } - static CompletableFuture> executeAsynchronousHttpRequest(HttpCommunicationConfiguration configuration, @Nullable RequestType request) { + static CompletableFuture> executeAsynchronousHttpRequest(HttpCommunicationConfiguration configuration, @Nullable RequestType request) { HttpUriRequest httpUriRequest = buildRequest(configuration, request); if (isNull(httpUriRequest)) { return completedFuture(empty()); @@ -126,12 +126,12 @@ static CompletableFuture> exe private static void executeHttpUriRequest(HttpUriRequest httpUriRequest, CloseableHttpAsyncClient client, HttpAsynchronousClientCallback callback) { try { - if (httpClientModule().isEnableRawDataTracing()) { - LogbookHttpAsyncResponseConsumer logbookConsumer = new LogbookHttpAsyncResponseConsumer<>(createConsumer()); - client.execute(HttpAsyncMethods.create(httpUriRequest), logbookConsumer, callback); + if (!httpClientModule().isEnableRawDataTracing()) { + client.execute(httpUriRequest, callback); return; } - client.execute(httpUriRequest, callback); + LogbookHttpAsyncResponseConsumer logbookConsumer = new LogbookHttpAsyncResponseConsumer<>(createConsumer()); + client.execute(HttpAsyncMethods.create(httpUriRequest), logbookConsumer, callback); } catch (Exception throwable) { throw new HttpClientException(throwable); } @@ -241,7 +241,7 @@ public void completed(HttpResponse result) { for (HttpClientInterceptor responseInterceptor : responseInterceptors) { InterceptionStrategy strategy = responseInterceptor.interceptResponse(httpUriRequest, result); if (strategy == PROCESS_HANDLING) break; - if (strategy == STOP_HANDLING){ + if (strategy == STOP_HANDLING) { completableFuture.complete(empty()); return; } diff --git a/application-http-client/src/main/java/ru/art/http/client/communicator/HttpCommunicatorImplementation.java b/application-http-client/src/main/java/ru/art/http/client/communicator/HttpCommunicatorImplementation.java index 02546cc7a..b800b9fff 100644 --- a/application-http-client/src/main/java/ru/art/http/client/communicator/HttpCommunicatorImplementation.java +++ b/application-http-client/src/main/java/ru/art/http/client/communicator/HttpCommunicatorImplementation.java @@ -18,10 +18,12 @@ package ru.art.http.client.communicator; +import lombok.*; import org.apache.http.HttpVersion; import org.apache.http.client.config.RequestConfig; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; +import org.apache.logging.log4j.*; import ru.art.core.validator.BuilderValidator; import ru.art.entity.Value; import ru.art.entity.interceptor.ValueInterceptor; @@ -35,6 +37,7 @@ import ru.art.http.client.model.HttpCommunicationTargetConfiguration; import ru.art.http.constants.MimeToContentTypeMapper; import static java.util.Optional.ofNullable; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.caster.Caster.cast; import static ru.art.core.checker.CheckerForEmptiness.isNotEmpty; import static ru.art.core.constants.StringConstants.COLON; @@ -55,6 +58,8 @@ public class HttpCommunicatorImplementation implements HttpCommunicator, HttpAsynchronousCommunicator { private final BuilderValidator validator = new BuilderValidator(HttpCommunicator.class.getName()); private final HttpCommunicationConfiguration configuration = new HttpCommunicationConfiguration(); + @Getter(lazy = true, value = PRIVATE) + private final static Logger logger = loggingModule().getLogger(HttpCommunicator.class); HttpCommunicatorImplementation(String url) { this(HttpCommunicationTargetConfiguration.httpCommunicationTarget().build().url(url)); @@ -239,7 +244,7 @@ public HttpCommunicator addResponseValueInterceptor(ValueInterceptor Optional execute() { @Override public void closeAsynchronousClient() { - ignoreException(configuration.getAsynchronousClient()::close, loggingModule().getLogger(HttpCommunicator.class)::error); + ignoreException(configuration.getAsynchronousClient()::close, getLogger()::error); } @Override diff --git a/application-http-client/src/main/java/ru/art/http/client/configuration/HttpClientModuleConfiguration.java b/application-http-client/src/main/java/ru/art/http/client/configuration/HttpClientModuleConfiguration.java index 6696ff87b..c4b03fbec 100644 --- a/application-http-client/src/main/java/ru/art/http/client/configuration/HttpClientModuleConfiguration.java +++ b/application-http-client/src/main/java/ru/art/http/client/configuration/HttpClientModuleConfiguration.java @@ -18,49 +18,38 @@ package ru.art.http.client.configuration; -import lombok.Getter; -import org.apache.http.HttpVersion; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.config.ConnectionConfig; -import org.apache.http.config.SocketConfig; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; -import org.apache.http.impl.nio.client.HttpAsyncClients; -import org.apache.http.impl.nio.reactor.IOReactorConfig; -import org.zalando.logbook.httpclient.LogbookHttpRequestInterceptor; -import org.zalando.logbook.httpclient.LogbookHttpResponseInterceptor; -import ru.art.http.client.exception.HttpClientException; -import ru.art.http.client.interceptor.HttpClientInterceptor; -import ru.art.http.client.interceptor.HttpClientTracingIdentifiersRequestInterception; -import ru.art.http.client.model.HttpCommunicationTargetConfiguration; -import ru.art.http.configuration.HttpModuleConfiguration; -import static java.security.KeyStore.getInstance; -import static java.text.MessageFormat.format; -import static java.util.Collections.emptyMap; -import static java.util.Objects.nonNull; -import static org.apache.http.HttpVersion.HTTP_1_1; -import static org.apache.http.ssl.SSLContexts.custom; -import static ru.art.core.constants.NetworkConstants.LOCALHOST; -import static ru.art.core.constants.StringConstants.EMPTY_STRING; -import static ru.art.core.extension.ExceptionExtensions.exceptionIfNull; -import static ru.art.core.factory.CollectionsFactory.linkedListOf; -import static ru.art.http.client.constants.HttpClientExceptionMessages.HTTP_COMMUNICATION_TARGET_NOT_FOUND; -import static ru.art.http.client.constants.HttpClientExceptionMessages.HTTP_SSL_CONFIGURATION_FAILED; -import static ru.art.http.client.constants.HttpClientModuleConstants.RESPONSE_BUFFER_DEFAULT_SIZE; -import static ru.art.http.client.interceptor.HttpClientInterceptor.interceptRequest; -import static ru.art.http.client.module.HttpClientModule.httpClientModuleState; -import static ru.art.http.constants.HttpCommonConstants.DEFAULT_HTTP_PORT; -import static ru.art.logging.LoggingModule.loggingModule; -import javax.net.ssl.HostnameVerifier; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.security.KeyStore; -import java.util.List; -import java.util.Map; +import lombok.*; +import org.apache.http.*; +import org.apache.http.client.config.*; +import org.apache.http.config.*; +import org.apache.http.impl.client.*; +import org.apache.http.impl.nio.client.*; +import org.apache.http.impl.nio.reactor.*; +import org.zalando.logbook.httpclient.*; +import ru.art.http.client.exception.*; +import ru.art.http.client.interceptor.*; +import ru.art.http.client.model.*; +import ru.art.http.configuration.*; +import static java.security.KeyStore.*; +import static java.text.MessageFormat.*; +import static java.util.Collections.*; +import static java.util.Objects.*; +import static org.apache.http.HttpVersion.*; +import static org.apache.http.ssl.SSLContexts.*; +import static ru.art.core.constants.NetworkConstants.*; +import static ru.art.core.constants.StringConstants.*; +import static ru.art.core.extension.ExceptionExtensions.*; +import static ru.art.core.factory.CollectionsFactory.*; +import static ru.art.http.client.constants.HttpClientExceptionMessages.*; +import static ru.art.http.client.constants.HttpClientModuleConstants.*; +import static ru.art.http.client.interceptor.HttpClientInterceptor.*; +import static ru.art.http.client.module.HttpClientModule.*; +import static ru.art.http.constants.HttpCommonConstants.*; +import static ru.art.logging.LoggingModule.*; +import javax.net.ssl.*; +import java.io.*; +import java.security.*; +import java.util.*; public interface HttpClientModuleConfiguration extends HttpModuleConfiguration { CloseableHttpClient getClient(); @@ -151,9 +140,7 @@ protected CloseableHttpAsyncClient createAsyncHttpClient() { throw new HttpClientException(HTTP_SSL_CONFIGURATION_FAILED, throwable); } } - if (this.isEnableRawDataTracing()) { - clientBuilder.addInterceptorFirst(new LogbookHttpRequestInterceptor(getLogbook())); - } + clientBuilder.addInterceptorFirst(new LogbookHttpRequestInterceptor(getLogbook())); CloseableHttpAsyncClient client = httpClientModuleState().registerClient(clientBuilder.build()); client.start(); return client; @@ -164,11 +151,9 @@ protected CloseableHttpClient createHttpClient() { HttpClientBuilder clientBuilder = HttpClients.custom() .setDefaultRequestConfig(getRequestConfig()) .setDefaultConnectionConfig(getConnectionConfig()) - .setDefaultSocketConfig(getSocketConfig()); - if (this.isEnableRawDataTracing()) { - clientBuilder.addInterceptorFirst(new LogbookHttpRequestInterceptor(getLogbook())) - .addInterceptorLast(new LogbookHttpResponseInterceptor()); - } + .setDefaultSocketConfig(getSocketConfig()) + .addInterceptorFirst(new LogbookHttpRequestInterceptor(getLogbook())) + .addInterceptorLast(new LogbookHttpResponseInterceptor()); if (isSsl()) { try { if (disableSslHostNameVerification) { diff --git a/application-http-client/src/main/java/ru/art/http/client/constants/HttpClientModuleConstants.java b/application-http-client/src/main/java/ru/art/http/client/constants/HttpClientModuleConstants.java index 507d6e53b..9f572bbd4 100644 --- a/application-http-client/src/main/java/ru/art/http/client/constants/HttpClientModuleConstants.java +++ b/application-http-client/src/main/java/ru/art/http/client/constants/HttpClientModuleConstants.java @@ -19,7 +19,7 @@ package ru.art.http.client.constants; public interface HttpClientModuleConstants { - String HTTP_CLIENT_CLOSING = "Closing HTTP client for ''{0}''"; + String HTTP_CLIENT_CLOSING = "Closing HTTP client"; String HTTP_COMMUNICATION_SERVICE_TYPE = "HTTP_COMMUNICATION"; String HTTP_CLIENT_MODULE_ID = "HTTP_CLIENT_MODULE"; String TRACE_ID_HEADER = "X-Trace-Id"; diff --git a/application-http-client/src/main/java/ru/art/http/client/factory/HttpClientsFactory.java b/application-http-client/src/main/java/ru/art/http/client/factory/HttpClientsFactory.java index 1e0bf018c..a2115db1d 100644 --- a/application-http-client/src/main/java/ru/art/http/client/factory/HttpClientsFactory.java +++ b/application-http-client/src/main/java/ru/art/http/client/factory/HttpClientsFactory.java @@ -18,30 +18,22 @@ package ru.art.http.client.factory; -import lombok.experimental.UtilityClass; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.client.HttpClientBuilder; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.http.impl.nio.client.HttpAsyncClientBuilder; -import org.apache.http.impl.nio.client.HttpAsyncClients; -import org.zalando.logbook.httpclient.LogbookHttpRequestInterceptor; -import org.zalando.logbook.httpclient.LogbookHttpResponseInterceptor; -import ru.art.http.client.configuration.HttpClientModuleConfiguration; -import ru.art.http.client.exception.HttpClientException; -import ru.art.http.client.model.HttpClientConfiguration; -import static java.security.KeyStore.getInstance; -import static java.util.Objects.nonNull; -import static org.apache.http.ssl.SSLContexts.custom; -import static ru.art.http.client.constants.HttpClientExceptionMessages.HTTP_SSL_CONFIGURATION_FAILED; -import static ru.art.http.client.module.HttpClientModule.httpClientModule; -import static ru.art.http.client.module.HttpClientModule.httpClientModuleState; -import static ru.art.logging.LoggingModule.loggingModule; -import javax.net.ssl.HostnameVerifier; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.security.KeyStore; +import lombok.experimental.*; +import org.apache.http.impl.client.*; +import org.apache.http.impl.nio.client.*; +import org.zalando.logbook.httpclient.*; +import ru.art.http.client.configuration.*; +import ru.art.http.client.exception.*; +import ru.art.http.client.model.*; +import static java.security.KeyStore.*; +import static java.util.Objects.*; +import static org.apache.http.ssl.SSLContexts.*; +import static ru.art.http.client.constants.HttpClientExceptionMessages.*; +import static ru.art.http.client.module.HttpClientModule.*; +import static ru.art.logging.LoggingModule.*; +import javax.net.ssl.*; +import java.io.*; +import java.security.*; @UtilityClass public class HttpClientsFactory { @@ -64,10 +56,9 @@ public static CloseableHttpAsyncClient createAsyncHttpClient(HttpClientConfigura throw new HttpClientException(HTTP_SSL_CONFIGURATION_FAILED, throwable); } } - if (configuration.isEnableRawDataTracing()) { - clientBuilder.addInterceptorFirst(new LogbookHttpRequestInterceptor(httpClientModule().getLogbook())) - .addInterceptorLast(new LogbookHttpResponseInterceptor()); - } + clientBuilder + .addInterceptorFirst(new LogbookHttpRequestInterceptor(httpClientModule().getLogbook())) + .addInterceptorLast(new LogbookHttpResponseInterceptor()); CloseableHttpAsyncClient client = httpClientModuleState().registerClient(clientBuilder.build()); client.start(); return client; @@ -78,11 +69,9 @@ public static CloseableHttpClient createHttpClient(HttpClientConfiguration confi HttpClientBuilder clientBuilder = HttpClients.custom() .setDefaultRequestConfig(configuration.getRequestConfig()) .setDefaultConnectionConfig(configuration.getConnectionConfig()) - .setDefaultSocketConfig(configuration.getSocketConfig()); - if (configuration.isEnableRawDataTracing()) { - clientBuilder.addInterceptorFirst(new LogbookHttpRequestInterceptor(httpClientModule().getLogbook())) - .addInterceptorLast(new LogbookHttpResponseInterceptor()); - } + .setDefaultSocketConfig(configuration.getSocketConfig()) + .addInterceptorFirst(new LogbookHttpRequestInterceptor(httpClientModule().getLogbook())) + .addInterceptorLast(new LogbookHttpResponseInterceptor()); if (configuration.isSsl()) { try { if (configuration.isDisableSslHostNameVerification()) { diff --git a/application-http-client/src/main/java/ru/art/http/client/module/HttpClientModule.java b/application-http-client/src/main/java/ru/art/http/client/module/HttpClientModule.java index b0b6bf7a3..0418dd063 100644 --- a/application-http-client/src/main/java/ru/art/http/client/module/HttpClientModule.java +++ b/application-http-client/src/main/java/ru/art/http/client/module/HttpClientModule.java @@ -45,7 +45,8 @@ public class HttpClientModule implements Module lastRequestInterceptionResult = new ThreadLocal<>(); - private final static ThreadLocal lastResponseInterceptionResult = new ThreadLocal<>(); + private final Map requestInterceptionsResult = concurrentHashMap(); + private final Map responseInterceptionsResult = concurrentHashMap(); private final Deque requestInterceptors; private final Deque responseInterceptors; private final Set cancelablePaths = setOf(); private final Tomcat tomcat; - private final Logger logger; + @Getter(lazy = true, value = PRIVATE) + private final static Logger logger = loggingModule().getLogger(HttpServer.class); private HttpServer(Tomcat tomcat) { this.tomcat = tomcat; tomcat.setBaseDir(getProperty(TEMP_DIR_KEY)); - logger = loggingModule().getLogger(HttpServer.class); requestInterceptors = dequeOf(); responseInterceptors = dequeOf(); httpServerModuleState().setServer(this); @@ -123,9 +125,9 @@ public void restart() { try { tomcat.stop(); startHttpServer(); - logger.info(format(TOMCAT_RESTARTED_MESSAGE, currentTimeMillis() - millis)); + getLogger().info(format(TOMCAT_RESTARTED_MESSAGE, currentTimeMillis() - millis)); } catch (Throwable throwable) { - logger.error(TOMCAT_RESTARTING_FAILED); + getLogger().error(TOMCAT_RESTARTING_FAILED); } } @@ -133,9 +135,9 @@ public void stop() { long millis = currentTimeMillis(); try { tomcat.stop(); - logger.info(format(TOMCAT_STOPPED_MESSAGE, currentTimeMillis() - millis)); + getLogger().info(format(TOMCAT_STOPPED_MESSAGE, currentTimeMillis() - millis)); } catch (Throwable throwable) { - logger.error(TOMCAT_STOPPING_FAILED); + getLogger().error(TOMCAT_STOPPING_FAILED); } } @@ -143,7 +145,7 @@ private Context createContext() { StandardContext ctx = (StandardContext) tomcat.addContext(EMPTY_STRING, getProperty(TEMP_DIR_KEY)); ctx.setAllowCasualMultipartParsing(httpServerModule().isAllowCasualMultipartParsing()); if (cancelablePaths.contains(SLASH)) { - logger.info(HTTP_SERVICES_CANCELED); + getLogger().info(HTTP_SERVICES_CANCELED); return ctx; } ctx.setClearReferencesObjectStreamClassCaches(false); @@ -160,7 +162,7 @@ private void registerHttpServices(Context ctx) { private void registerService(String serviceId, HttpServiceSpecification serviceSpec, Context ctx) { HttpService httpService = serviceSpec.getHttpService(); if (cancelablePaths.contains(httpService.getPath())) { - logger.info(format(HTTP_SERVICE_CANCELED, serviceId, httpService.getPath())); + getLogger().info(format(HTTP_SERVICE_CANCELED, serviceId, httpService.getPath())); return; } @@ -180,7 +182,7 @@ private void registerService(String serviceId, HttpServiceSpecification serviceS } HttpPath path = buildHttpPath(extractHttpServicePath(serviceSpec), method.getPath()); if (cancelablePaths.contains(path.toString())) { - logger.info(format(HTTP_SERVICE_METHOD_CANCELED, serviceId, method.getMethodId(), httpService.getPath())); + getLogger().info(format(HTTP_SERVICE_METHOD_CANCELED, serviceId, method.getMethodId(), httpService.getPath())); continue; } Wrapper defaultServlet = ctx.createWrapper(); @@ -211,7 +213,7 @@ private void logHttpServiceRegistration(HttpServiceSpecification serviceSpec, Ma .scheme(HTTP_SCHEME) .uri(path.toString()) .build(); - logger.info(format(HTTP_SERVICE_REGISTERING_MESSAGE, buildUrl(urlInfo), serviceSpec.getServiceId(), methods.keySet())); + getLogger().info(format(HTTP_SERVICE_REGISTERING_MESSAGE, buildUrl(urlInfo), serviceSpec.getServiceId(), methods.keySet())); } catch (Throwable throwable) { throw new HttpServerException(throwable); } @@ -247,7 +249,7 @@ private void startup() throws LifecycleException { bindHttpMetrics(context.getManager()); } tomcat.start(); - logger.info(format(TOMCAT_STARTED_MESSAGE, currentTimeMillis() - timestamp)); + getLogger().info(format(TOMCAT_STARTED_MESSAGE, currentTimeMillis() - timestamp)); } private void configureConnector() { @@ -286,15 +288,11 @@ private void registerInterceptors(Context context) { if (interceptor.getInterceptor().getStrategy() == PROCESS_HANDLING) break; if (interceptor.getInterceptor().getStrategy() == STOP_HANDLING) { cancelablePaths.add(interceptor.getPath()); - if (httpServerModule().isEnableRawDataTracing()) { - addLoggingFilter(context); - } + addLoggingFilter(context); return; } } - if (httpServerModule().isEnableRawDataTracing()) { - addLoggingFilter(context); - } + addLoggingFilter(context); order = 0; while (!responseInterceptors.isEmpty()) { HttpServerPathInterceptor interceptor = responseInterceptors.removeLast(); @@ -354,14 +352,14 @@ private HttpServerPathInterceptor createHttpInterceptor(String servicePath, Http private void registerBeforeInterceptor(Context context, HttpServerPathInterceptor serverPathInterceptor, String filterName) { String urlPattern = ifNotEquals(serverPathInterceptor.getPath(), SLASH, serverPathInterceptor.getPath() + SLASH) + WILDCARD; - logger.info(format(REGISTERING_HTTP_INTERCEPTOR, filterName, urlPattern)); + getLogger().info(format(REGISTERING_HTTP_INTERCEPTOR, filterName, urlPattern)); FilterDef def = new FilterDef(); def.setFilterName(filterName); Filter filter = (request, response, chain) -> { - InterceptionStrategy strategy = lastRequestInterceptionResult.get(); + InterceptionStrategy strategy = requestInterceptionsResult.get(filterName); if (isNull(strategy) || strategy == NEXT_INTERCEPTOR) { - lastRequestInterceptionResult - .set(serverPathInterceptor.getInterceptor().intercept((HttpServletRequest) request, (HttpServletResponse) response)); + InterceptionStrategy nextInterceptionStrategy = serverPathInterceptor.getInterceptor().intercept((HttpServletRequest) request, (HttpServletResponse) response); + requestInterceptionsResult.put(filterName, nextInterceptionStrategy); chain.doFilter(request, response); return; } @@ -379,15 +377,15 @@ private void registerBeforeInterceptor(Context context, HttpServerPathIntercepto private void registerAfterInterceptor(Context context, HttpServerPathInterceptor serverInterceptor, String filterName) { String urlPattern = ifNotEquals(serverInterceptor.getPath(), SLASH, serverInterceptor.getPath() + SLASH) + WILDCARD; - logger.info(format(REGISTERING_HTTP_INTERCEPTOR, filterName, urlPattern)); + getLogger().info(format(REGISTERING_HTTP_INTERCEPTOR, filterName, urlPattern)); FilterDef def = new FilterDef(); def.setFilterName(filterName); def.setFilter((request, response, chain) -> { - InterceptionStrategy strategy = lastResponseInterceptionResult.get(); + InterceptionStrategy strategy = responseInterceptionsResult.get(filterName); if (isNull(strategy) || strategy == NEXT_INTERCEPTOR) { chain.doFilter(request, response); - lastResponseInterceptionResult - .set(serverInterceptor.getInterceptor().intercept((HttpServletRequest) request, (HttpServletResponse) response)); + InterceptionStrategy nextInterceptionStrategy = serverInterceptor.getInterceptor().intercept((HttpServletRequest) request, (HttpServletResponse) response); + responseInterceptionsResult.put(filterName, nextInterceptionStrategy); return; } if (strategy == PROCESS_HANDLING) { diff --git a/application-http-server/src/main/java/ru/art/http/server/HttpServerModuleConfiguration.java b/application-http-server/src/main/java/ru/art/http/server/HttpServerModuleConfiguration.java index 78994733b..de5c4a34d 100644 --- a/application-http-server/src/main/java/ru/art/http/server/HttpServerModuleConfiguration.java +++ b/application-http-server/src/main/java/ru/art/http/server/HttpServerModuleConfiguration.java @@ -42,6 +42,7 @@ import static ru.art.http.server.interceptor.HttpServerInterceptor.*; import java.nio.charset.*; import java.util.*; +import java.util.function.*; public interface HttpServerModuleConfiguration extends HttpModuleConfiguration { static List initializeWebServerInterceptors(List parents) { @@ -49,12 +50,16 @@ static List initializeWebServerInterceptors(List enabled) { + return builder + .rawResponseFilter(replaceBody(HttpResourceLogsFilter::replaceResponseBody)) + .writer(new ZalangoLogbookLogWriter(enabled)); } - static LogbookCreator.Builder logbookWithoutResourceLogs() { - return Logbook.builder().rawResponseFilter(replaceBody(HttpResourceLogsFilter::replaceResponseBody)).writer(new ZalangoLogbookLogWriter()); + static LogbookCreator.Builder logbookWithoutResourceLogs(Supplier enabled) { + return Logbook.builder() + .rawResponseFilter(replaceBody(HttpResourceLogsFilter::replaceResponseBody)) + .writer(new ZalangoLogbookLogWriter(enabled)); } String getHost(); diff --git a/application-http-server/src/main/java/ru/art/http/server/specification/HttpResourceServiceSpecification.java b/application-http-server/src/main/java/ru/art/http/server/specification/HttpResourceServiceSpecification.java index 0791ac5f9..1c3c4b6f3 100644 --- a/application-http-server/src/main/java/ru/art/http/server/specification/HttpResourceServiceSpecification.java +++ b/application-http-server/src/main/java/ru/art/http/server/specification/HttpResourceServiceSpecification.java @@ -28,6 +28,7 @@ import ru.art.service.exception.*; import ru.art.service.interceptor.ServiceExecutionInterceptor.*; import ru.art.service.model.*; +import static lombok.AccessLevel.*; import static ru.art.core.caster.Caster.*; import static ru.art.core.constants.StringConstants.*; import static ru.art.core.extension.NullCheckingExtensions.*; @@ -58,7 +59,8 @@ public class HttpResourceServiceSpecification implements HttpServiceSpecificatio private final HttpService httpService = httpService() .get(GET_RESOURCE) .fromPathParameters(RESOURCE) - .requestMapper((StringParametersMapToModelMapper) resource -> doIfNotNull(resource, (Function) res -> resource.getParameter(RESOURCE))) + .requestMapper((StringParametersMapToModelMapper) resource -> doIfNotNull(resource, + (Function) res -> resource.getParameter(RESOURCE))) .overrideResponseContentType() .responseMapper(Caster::cast) .addRequestInterceptor(intercept(interceptAndContinue(((request, response) -> response.setContentType(extractTypeByFile(request.getRequestURI())))))) diff --git a/application-http/src/main/java/ru/art/http/configuration/HttpModuleConfiguration.java b/application-http/src/main/java/ru/art/http/configuration/HttpModuleConfiguration.java index ad65c89b5..07bb033d8 100644 --- a/application-http/src/main/java/ru/art/http/configuration/HttpModuleConfiguration.java +++ b/application-http/src/main/java/ru/art/http/configuration/HttpModuleConfiguration.java @@ -65,10 +65,10 @@ class HttpModuleDefaultConfiguration implements HttpModuleConfiguration { @Getter(lazy = true, onMethod = @__({@SuppressWarnings("unchecked")})) private final List> responseValueInterceptors = initializeValueInterceptors(); @Getter(lazy = true) - private final Logbook logbook = Logbook.builder().writer(new ZalangoLogbookLogWriter()).build(); + private final Logbook logbook = Logbook.builder().writer(new ZalangoLogbookLogWriter(this::isEnableRawDataTracing)).build(); private List> initializeValueInterceptors() { - return isEnableValueTracing() ? linkedListOf(new LoggingValueInterceptor<>()) : linkedListOf(); + return linkedListOf(new LoggingValueInterceptor<>(this::isEnableValueTracing)); } } } \ No newline at end of file diff --git a/application-http/src/main/java/ru/art/http/logger/ZalangoLogbookLogWriter.java b/application-http/src/main/java/ru/art/http/logger/ZalangoLogbookLogWriter.java index 3f9fcac22..e180da52f 100644 --- a/application-http/src/main/java/ru/art/http/logger/ZalangoLogbookLogWriter.java +++ b/application-http/src/main/java/ru/art/http/logger/ZalangoLogbookLogWriter.java @@ -27,19 +27,21 @@ @SuppressWarnings("SameParameterValue") public class ZalangoLogbookLogWriter implements HttpLogWriter { + private final Supplier enabled; private final Logger logger; private final Predicate activator; private final BiConsumer consumer; - public ZalangoLogbookLogWriter() { - this(loggingModule().getLogger(ZalangoLogbookLogWriter.class)); + public ZalangoLogbookLogWriter(Supplier enabled) { + this(loggingModule().getLogger(ZalangoLogbookLogWriter.class), enabled); } - private ZalangoLogbookLogWriter(final Logger logger) { - this(logger, INFO); + private ZalangoLogbookLogWriter(final Logger logger, Supplier enabled) { + this(enabled, logger, INFO); } - private ZalangoLogbookLogWriter(final Logger logger, final Level level) { + private ZalangoLogbookLogWriter(Supplier enabled, final Logger logger, final Level level) { + this.enabled = enabled; this.logger = logger; this.activator = chooseActivator(level); this.consumer = chooseConsumer(level); @@ -79,7 +81,7 @@ private static BiConsumer chooseConsumer(final Level level) { @Override public boolean isActive(final RawHttpRequest request) { - return activator.test(logger); + return enabled.get() && activator.test(logger); } @Override diff --git a/application-information/src/main/java/ru/art/information/module/InformationModule.java b/application-information/src/main/java/ru/art/information/module/InformationModule.java index 24bdd13c4..997e0d228 100644 --- a/application-information/src/main/java/ru/art/information/module/InformationModule.java +++ b/application-information/src/main/java/ru/art/information/module/InformationModule.java @@ -22,6 +22,7 @@ import ru.art.core.module.Module; import ru.art.core.module.*; import ru.art.information.configuration.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.context.Context.*; import static ru.art.information.configuration.InformationModuleConfiguration.*; import static ru.art.information.constants.InformationModuleConstants.*; @@ -30,7 +31,7 @@ public class InformationModule implements Module { private final String id = INFORMATION_MODULE_ID; private final InformationModuleConfiguration defaultConfiguration = new InformationModuleDefaultConfiguration(); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private final static InformationModuleConfiguration informationModule = context().getModule(INFORMATION_MODULE_ID, InformationModule::new); public static InformationModuleConfiguration informationModule() { diff --git a/application-information/src/main/web/src/component/EntityComponent.tsx b/application-information/src/main/web/src/component/EntityComponent.tsx index 44fca7c16..05b99d6a9 100644 --- a/application-information/src/main/web/src/component/EntityComponent.tsx +++ b/application-information/src/main/web/src/component/EntityComponent.tsx @@ -16,15 +16,8 @@ * limitations under the License. */ -import React from "react"; -import { - Chip, - ExpansionPanel, - ExpansionPanelDetails, - ExpansionPanelSummary, - Typography, - useTheme -} from "@material-ui/core"; +import React, {useMemo} from "react"; +import {Chip, ExpansionPanel, ExpansionPanelDetails, ExpansionPanelSummary, Typography, useTheme} from "@material-ui/core"; import ExpandMore from "@material-ui/icons/ExpandMore"; import ReactJson from "react-json-view"; @@ -40,24 +33,24 @@ export enum EntityType { export const EntityComponent = (props: EntityComponentProps) => { const theme = useTheme(); - const getEntity =() => { + const entity = useMemo(() => { const entityJson = JSON.parse(props.entity); if (typeof entityJson != "object") { return props.entity } return - }; + displayObjectSize={false} + displayDataTypes={false} + name={props.type == EntityType.REQUEST ? "request" : "response"} + src={entityJson}/> + }, [props.entity]); return }> {props.type == EntityType.REQUEST ? "Пример запроса" : "Пример ответа"}}/> - {getEntity()} + {entity} ; }; diff --git a/application-information/src/main/web/src/component/GrpcServiceComponent.tsx b/application-information/src/main/web/src/component/GrpcServiceComponent.tsx index 9b487f450..b0ba44566 100644 --- a/application-information/src/main/web/src/component/GrpcServiceComponent.tsx +++ b/application-information/src/main/web/src/component/GrpcServiceComponent.tsx @@ -33,14 +33,14 @@ import { import ExpandMore from "@material-ui/icons/ExpandMore"; import {GRPC_CHIP_STYLE} from "../constants/Constants"; import {GrpcMethodComponent} from "./GrpcMethodComponent"; -import {GrpcInformation, GrpcServiceInformation} from "../model/Models"; +import {GrpcInformation, GrpcServiceInformation, GrpcServiceMethodInformation} from "../model/Models"; interface GrpcServiceComponentProps { information: GrpcInformation, serviceInformation: GrpcServiceInformation } -const useStyles = makeStyles((theme: Theme) => createStyles({ +const useStyles = makeStyles(() => createStyles({ chip: GRPC_CHIP_STYLE })); diff --git a/application-kafka-consumer/src/main/java/ru/art/kafka/consumer/module/KafkaConsumerModule.java b/application-kafka-consumer/src/main/java/ru/art/kafka/consumer/module/KafkaConsumerModule.java index d0fb50c90..9485c9fa4 100644 --- a/application-kafka-consumer/src/main/java/ru/art/kafka/consumer/module/KafkaConsumerModule.java +++ b/application-kafka-consumer/src/main/java/ru/art/kafka/consumer/module/KafkaConsumerModule.java @@ -19,24 +19,23 @@ package ru.art.kafka.consumer.module; import lombok.*; -import org.apache.kafka.streams.KafkaStreams; -import org.apache.logging.log4j.Logger; +import org.apache.kafka.streams.*; +import org.apache.logging.log4j.*; import ru.art.core.module.Module; import ru.art.kafka.consumer.configuration.*; -import ru.art.kafka.consumer.model.ManagedKafkaConsumer; -import ru.art.kafka.consumer.model.ManagedKafkaStream; +import ru.art.kafka.consumer.model.*; import ru.art.kafka.consumer.registry.*; import ru.art.kafka.consumer.specification.*; import ru.art.kafka.consumer.state.*; -import static java.text.MessageFormat.format; +import static java.text.MessageFormat.*; import static java.util.stream.Collectors.*; import static lombok.AccessLevel.*; import static ru.art.core.caster.Caster.*; import static ru.art.core.context.Context.*; -import static ru.art.core.wrapper.ExceptionWrapper.ignoreException; +import static ru.art.core.wrapper.ExceptionWrapper.*; import static ru.art.kafka.consumer.configuration.KafkaConsumerModuleConfiguration.*; import static ru.art.kafka.consumer.constants.KafkaConsumerModuleConstants.*; -import static ru.art.logging.LoggingModule.loggingModule; +import static ru.art.logging.LoggingModule.*; import static ru.art.service.ServiceModule.*; import java.util.*; @@ -44,7 +43,7 @@ public class KafkaConsumerModule implements Module { @Getter(lazy = true, onMethod = @__({@SuppressWarnings("unchecked")}), value = PRIVATE) private final static List kafkaConsumerServices = cast(serviceModuleState() - .getServiceRegistry() + .getServiceRegistry() .getServices() .values() .stream() @@ -58,7 +57,8 @@ public class KafkaConsumerModule implements Module entry) { - logger.info(format(CLOSING_KAFKA_CONSUMER, entry.getKey())); + getLogger().info(format(CLOSING_KAFKA_CONSUMER, entry.getKey())); ignoreException(entry.getValue().getConsumer()::close); } private void stopStream(Map.Entry entry) { - logger.info(format(CLOSING_KAFKA_STREAMS, entry.getKey())); + getLogger().info(format(CLOSING_KAFKA_STREAMS, entry.getKey())); ignoreException(entry.getValue().getKafkaStreams()::close); } } diff --git a/application-kafka-consumer/src/main/java/ru/art/kafka/consumer/registry/KafkaStreamsRegistry.java b/application-kafka-consumer/src/main/java/ru/art/kafka/consumer/registry/KafkaStreamsRegistry.java index 4dba953ca..77f67103c 100644 --- a/application-kafka-consumer/src/main/java/ru/art/kafka/consumer/registry/KafkaStreamsRegistry.java +++ b/application-kafka-consumer/src/main/java/ru/art/kafka/consumer/registry/KafkaStreamsRegistry.java @@ -28,6 +28,7 @@ import ru.art.kafka.consumer.model.*; import static java.lang.String.*; import static java.text.MessageFormat.format; +import static lombok.AccessLevel.PRIVATE; import static org.apache.kafka.streams.StreamsConfig.*; import static org.apache.logging.log4j.ThreadContext.*; import static ru.art.core.checker.CheckerForEmptiness.isEmpty; @@ -45,6 +46,7 @@ @Getter public class KafkaStreamsRegistry { private final Map streams = concurrentHashMap(); + @Getter(lazy = true, value = PRIVATE) private static final Logger logger = loggingModule().getLogger(KafkaStreamsRegistry.class); public static KStream withTracing(KStream stream) { @@ -57,7 +59,7 @@ private static void logKafkaRecord(K key, V value) { } putIfNotNull(KAFKA_KEY, key); putIfNotNull(KAFKA_VALUE, value); - logger.info(format(KAFKA_TRACE_MESSAGE, key, value)); + getLogger().info(format(KAFKA_TRACE_MESSAGE, key, value)); remove(KAFKA_KEY); remove(KAFKA_VALUE); } diff --git a/application-logging/src/main/java/ru/art/logging/LoggerConfigurationService.java b/application-logging/src/main/java/ru/art/logging/LoggerConfigurationService.java index 5f3d1b71f..a8bf2e480 100644 --- a/application-logging/src/main/java/ru/art/logging/LoggerConfigurationService.java +++ b/application-logging/src/main/java/ru/art/logging/LoggerConfigurationService.java @@ -23,6 +23,7 @@ import org.apache.logging.log4j.core.*; import org.apache.logging.log4j.core.appender.*; import org.apache.logging.log4j.core.config.*; +import org.apache.logging.log4j.core.net.*; import static java.lang.Integer.*; import static java.lang.System.*; import static java.util.Objects.*; @@ -64,10 +65,12 @@ static SocketAppenderConfiguration loadSocketAppenderCurrentConfiguration() { if (isNull(socketAppender)) return SocketAppenderConfiguration.builder().build(); Map contentFormat = socketAppender.getManager().getContentFormat(); String host = contentFormat.get(ADDRESS); + String protocol = contentFormat.get(PROTOCOL); int port = parseInt(contentFormat.get(PORT)); return SocketAppenderConfiguration.builder() .host(host) .port(port) + .protocol(protocol) .layout(socketAppender.getLayout()) .build(); } @@ -112,6 +115,7 @@ static SocketAppender createLoadedSocketAppender() { .newBuilder() .setName(SocketAppender.class.getSimpleName()) .withHost(host) + .withProtocol(isEmpty(socketAppenderConfiguration) ? Protocol.TCP : Protocol.valueOf(socketAppenderConfiguration.getProtocol().toUpperCase())) .withPort(socketAppenderConfiguration.getPort()) .setLayout(socketAppenderConfiguration.getLayout()) .build(); diff --git a/application-logging/src/main/java/ru/art/logging/LoggingModuleConstants.java b/application-logging/src/main/java/ru/art/logging/LoggingModuleConstants.java index 298de9857..55941b6a1 100644 --- a/application-logging/src/main/java/ru/art/logging/LoggingModuleConstants.java +++ b/application-logging/src/main/java/ru/art/logging/LoggingModuleConstants.java @@ -22,6 +22,7 @@ public interface LoggingModuleConstants { String LOGGING_MODULE_ID = "LOGGING_MODULE"; String DEFAULT_REQUEST_ID = "DEFAULT_REQUEST_ID"; String PORT = "port"; + String PROTOCOL = "protocol"; String ADDRESS = "address"; String LOG4J2_YAML_FILE = "log4j2.yml"; String LOG4J2_CONFIGURATION_FILE_PROPERTY = "log4j.configurationFile"; diff --git a/application-logging/src/main/java/ru/art/logging/LoggingValueInterceptor.java b/application-logging/src/main/java/ru/art/logging/LoggingValueInterceptor.java index a7f1d1c91..0a726729f 100644 --- a/application-logging/src/main/java/ru/art/logging/LoggingValueInterceptor.java +++ b/application-logging/src/main/java/ru/art/logging/LoggingValueInterceptor.java @@ -18,7 +18,8 @@ package ru.art.logging; -import ru.art.entity.*; +import lombok.*; +import ru.art.entity.Value; import ru.art.entity.interceptor.*; import static java.text.MessageFormat.*; import static org.apache.logging.log4j.ThreadContext.*; @@ -28,14 +29,20 @@ import static ru.art.logging.LoggingModuleConstants.LoggingParameters.*; import static ru.art.logging.LoggingModuleConstants.*; import static ru.art.logging.ThreadContextExtensions.*; +import java.util.function.*; +@AllArgsConstructor public class LoggingValueInterceptor implements ValueInterceptor { + private final Supplier enableTracing; + @Override public ValueInterceptionResult intercept(Value value) { putIfNotNull(REQUEST_VALUE_KEY, value); - loggingModule() - .getLogger(LoggingValueInterceptor.class) - .info(format(VALUE_LOG_MESSAGE, value)); + if (enableTracing.get()) { + loggingModule() + .getLogger(LoggingValueInterceptor.class) + .info(format(VALUE_LOG_MESSAGE, value)); + } remove(REQUEST_VALUE_KEY); return cast(nextInterceptor(value)); } diff --git a/application-logging/src/main/java/ru/art/logging/SocketAppenderConfiguration.java b/application-logging/src/main/java/ru/art/logging/SocketAppenderConfiguration.java index a42ce32d0..f27f5c2dc 100644 --- a/application-logging/src/main/java/ru/art/logging/SocketAppenderConfiguration.java +++ b/application-logging/src/main/java/ru/art/logging/SocketAppenderConfiguration.java @@ -25,6 +25,7 @@ @Builder public class SocketAppenderConfiguration { private final String host; + private final String protocol; private final int port; private final Layout layout; } diff --git a/application-metrics-http/src/main/java/ru/art/metrics/http/filter/MetricsHttpLogFilter.java b/application-metrics-http/src/main/java/ru/art/metrics/http/filter/MetricsHttpLogFilter.java index 389850039..25d764846 100644 --- a/application-metrics-http/src/main/java/ru/art/metrics/http/filter/MetricsHttpLogFilter.java +++ b/application-metrics-http/src/main/java/ru/art/metrics/http/filter/MetricsHttpLogFilter.java @@ -23,17 +23,18 @@ import ru.art.http.logger.*; import static org.zalando.logbook.Conditions.*; import static ru.art.metrics.constants.MetricsModuleConstants.*; +import java.util.function.*; public interface MetricsHttpLogFilter { - static Builder logbookWithoutMetricsLogs(Builder builder) { + static Builder logbookWithoutMetricsLogs(Builder builder, Supplier enabled) { return builder .condition(exclude(request -> request.getPath().contains(METRICS_PATH))) - .writer(new ZalangoLogbookLogWriter()); + .writer(new ZalangoLogbookLogWriter(enabled)); } - static Builder logbookWithoutMetricsLogs() { + static Builder logbookWithoutMetricsLogs(Supplier enabled) { return Logbook.builder() .condition(exclude(request -> request.getPath().contains(METRICS_PATH))) - .writer(new ZalangoLogbookLogWriter()); + .writer(new ZalangoLogbookLogWriter(enabled)); } } diff --git a/application-network-manager/src/main/java/ru/art/network/manager/module/NetworkManagerModule.java b/application-network-manager/src/main/java/ru/art/network/manager/module/NetworkManagerModule.java index beffa4de3..7bc601cfb 100644 --- a/application-network-manager/src/main/java/ru/art/network/manager/module/NetworkManagerModule.java +++ b/application-network-manager/src/main/java/ru/art/network/manager/module/NetworkManagerModule.java @@ -27,6 +27,7 @@ import ru.art.state.api.communication.grpc.*; import static java.time.Duration.*; import static java.time.temporal.ChronoUnit.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.context.Context.*; import static ru.art.network.manager.configuration.NetworkManagerModuleConfiguration.*; import static ru.art.network.manager.constants.NetworkManagerModuleConstants.*; @@ -36,9 +37,9 @@ @Getter public class NetworkManagerModule implements Module { - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private static final NetworkManagerModuleConfiguration networkManagerModule = context().getModule(NETWORK_MANAGER_MODULE_ID, NetworkManagerModule::new); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private static final NetworkManagerModuleState networkManagerModuleState = context().getModuleState(NETWORK_MANAGER_MODULE_ID, NetworkManagerModule::new); private final String id = NETWORK_MANAGER_MODULE_ID; private final NetworkManagerModuleConfiguration defaultConfiguration = NetworkManagerModuleDefaultConfiguration.DEFAULT_CONFIGURATION; diff --git a/application-reactive-service/src/main/java/ru/art/reactive/service/module/ReactiveServiceModule.java b/application-reactive-service/src/main/java/ru/art/reactive/service/module/ReactiveServiceModule.java index 9817a84fc..a2048538d 100644 --- a/application-reactive-service/src/main/java/ru/art/reactive/service/module/ReactiveServiceModule.java +++ b/application-reactive-service/src/main/java/ru/art/reactive/service/module/ReactiveServiceModule.java @@ -22,13 +22,14 @@ import ru.art.core.module.Module; import ru.art.core.module.*; import ru.art.reactive.service.configuration.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.context.Context.*; import static ru.art.reactive.service.configuration.ReactiveServiceModuleConfiguration.*; import static ru.art.reactive.service.constants.ReactiveServiceModuleConstants.*; @Getter public class ReactiveServiceModule implements Module { - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private static final ReactiveServiceModuleConfiguration reactiveServiceModule = context().getModule(REACTIVE_SERVICE_MODULE_ID, ReactiveServiceModule::new); private final String id = REACTIVE_SERVICE_MODULE_ID; private final ReactiveServiceModuleConfiguration defaultConfiguration = DEFAULT_CONFIGURATION; diff --git a/application-remote-scheduler/src/main/java/ru/art/remote/scheduler/action/TaskExecutionActions.java b/application-remote-scheduler/src/main/java/ru/art/remote/scheduler/action/TaskExecutionActions.java index 5da5c25c4..46e85bdca 100644 --- a/application-remote-scheduler/src/main/java/ru/art/remote/scheduler/action/TaskExecutionActions.java +++ b/application-remote-scheduler/src/main/java/ru/art/remote/scheduler/action/TaskExecutionActions.java @@ -39,7 +39,7 @@ public interface TaskExecutionActions { static void executeDeferredTask(DeferredTask task) { - loggingModule().getLogger().info(format(TASK_STARTED_MESSAGE, task)); + loggingModule().getLogger(TaskExecutionActions.class).info(format(TASK_STARTED_MESSAGE, task)); try { ServiceResponse response = grpcCommunicator(remoteSchedulerModule().getBalancerHost(), remoteSchedulerModule().getBalancerPort(), @@ -55,7 +55,7 @@ static void executeDeferredTask(DeferredTask task) { } static void submitPeriodicTask(PeriodicTask task) { - loggingModule().getLogger().info(format(TASK_STARTED_MESSAGE, task)); + loggingModule().getLogger(TaskExecutionActions.class).info(format(TASK_STARTED_MESSAGE, task)); try { ServiceResponse response = grpcCommunicator(remoteSchedulerModule().getBalancerHost(), remoteSchedulerModule().getBalancerPort(), @@ -71,7 +71,7 @@ static void submitPeriodicTask(PeriodicTask task) { } static void submitInfinityProcess(InfinityProcess process) { - loggingModule().getLogger().info(format(PROCESS_STARTED_MESSAGE, process)); + loggingModule().getLogger(TaskExecutionActions.class).info(format(PROCESS_STARTED_MESSAGE, process)); try { ServiceResponse response = grpcCommunicator(remoteSchedulerModule().getBalancerHost(), remoteSchedulerModule().getBalancerPort(), @@ -87,21 +87,21 @@ static void submitInfinityProcess(InfinityProcess process) { } static void handlePeriodicTaskError(Throwable error, PeriodicTask task) { - loggingModule().getLogger().error(format(TASK_FAILED_MESSAGE, task), error); + loggingModule().getLogger(TaskExecutionActions.class).error(format(TASK_FAILED_MESSAGE, task), error); handlePeriodicTaskAction(task); } static void handleDeferredTaskError(Throwable error, DeferredTask task) { - loggingModule().getLogger().error(format(TASK_FAILED_MESSAGE, task), error); + loggingModule().getLogger(TaskExecutionActions.class).error(format(TASK_FAILED_MESSAGE, task), error); executeServiceMethod(remoteSchedulerModule().getDbAdapterServiceId(), UPDATE_DEFERRED_TASK_STATUS, new UpdateTaskStatusRequest(task.getId(), FAILED)); } static void handleInfinityProcessError(Throwable error, InfinityProcess process) { - loggingModule().getLogger().error(format(PROCESS_FAILED_MESSAGE, process), error); + loggingModule().getLogger(TaskExecutionActions.class).error(format(PROCESS_FAILED_MESSAGE, process), error); } static void handlePeriodicTaskCompletion(PeriodicTask task, ServiceResponse response) { - loggingModule().getLogger().info(format(TASK_COMPLETED_MESSAGE, task, getOrElse(response.getResponseData(), EMPTY_STRING))); + loggingModule().getLogger(TaskExecutionActions.class).info(format(TASK_COMPLETED_MESSAGE, task, getOrElse(response.getResponseData(), EMPTY_STRING))); if (task.isFinishAfterCompletion()) { executeServiceMethod(remoteSchedulerModule().getDbAdapterServiceId(), INC_EXECUTION_COUNT, task.getId()); @@ -114,12 +114,12 @@ static void handlePeriodicTaskCompletion(PeriodicTask task, ServiceResponse response) { - loggingModule().getLogger().info(format(TASK_COMPLETED_MESSAGE, task, getOrElse(response.getResponseData(), EMPTY_STRING))); + loggingModule().getLogger(TaskExecutionActions.class).info(format(TASK_COMPLETED_MESSAGE, task, getOrElse(response.getResponseData(), EMPTY_STRING))); executeServiceMethod(remoteSchedulerModule().getDbAdapterServiceId(), UPDATE_DEFERRED_TASK_STATUS, new UpdateTaskStatusRequest(task.getId(), COMPLETED)); } static void handleInfinityProcessCompletion(InfinityProcess process, ServiceResponse response) { - loggingModule().getLogger().info(format(PROCESS_COMPLETED_MESSAGE, process, getOrElse(response.getResponseData(), EMPTY_STRING))); + loggingModule().getLogger(TaskExecutionActions.class).info(format(PROCESS_COMPLETED_MESSAGE, process, getOrElse(response.getResponseData(), EMPTY_STRING))); } static void updateTaskStatusProcessingIfFirstAttempt(String taskId, int currentRetryCount) { diff --git a/application-rsocket/src/main/java/ru/art/rsocket/communicator/RsocketCommunicator.java b/application-rsocket/src/main/java/ru/art/rsocket/communicator/RsocketCommunicator.java index 1c82b0ccc..58ac0b53c 100644 --- a/application-rsocket/src/main/java/ru/art/rsocket/communicator/RsocketCommunicator.java +++ b/application-rsocket/src/main/java/ru/art/rsocket/communicator/RsocketCommunicator.java @@ -37,6 +37,7 @@ import static java.text.MessageFormat.*; import static java.time.Duration.*; import static java.util.Optional.*; +import static lombok.AccessLevel.*; import static reactor.core.publisher.Flux.from; import static reactor.core.publisher.Mono.just; import static ru.art.core.caster.Caster.*; @@ -63,6 +64,7 @@ @RequiredArgsConstructor public class RsocketCommunicator { private final Mono rsocketMono; + @Getter(lazy = true, value = PRIVATE) private final static Logger logger = loggingModule().getLogger(RsocketCommunicator.class); private String serviceId; private String methodId; @@ -91,10 +93,9 @@ private RsocketCommunicator(RsocketCommunicationTargetConfiguration configuratio .transport(TcpClientTransport.create(configuration.host(), configuration.tcpPort())) .start() .doOnNext(rsocketModuleState()::registerRsocket) - .doOnSubscribe(subscription -> logger - .info(format(RSOCKET_TCP_COMMUNICATOR_STARTED_MESSAGE, configuration.host(), configuration.tcpPort()))); - logger.info(format(RSOCKET_TCP_COMMUNICATOR_CREATED_MESSAGE, configuration.host(), configuration.tcpPort())); - return; + .doOnSubscribe(subscription -> getLogger().info(format(RSOCKET_TCP_COMMUNICATOR_STARTED_MESSAGE, configuration.host(), configuration.tcpPort()))); + getLogger().info(format(RSOCKET_TCP_COMMUNICATOR_CREATED_MESSAGE, configuration.host(), configuration.tcpPort())); + return; case WEB_SOCKET: rsocketMono = factory .dataMimeType(toMimeType(configuration.dataFormat())) @@ -102,9 +103,8 @@ private RsocketCommunicator(RsocketCommunicationTargetConfiguration configuratio .transport(WebsocketClientTransport.create(configuration.host(), configuration.tcpPort())) .start() .doOnNext(rsocketModuleState()::registerRsocket) - .doOnSubscribe(subscription -> logger - .info(format(RSOCKET_WS_COMMUNICATOR_STARTED_MESSAGE, configuration.host(), configuration.webSocketPort()))); - logger.info(format(RSOCKET_WS_COMMUNICATOR_CREATED_MESSAGE, configuration.host(), configuration.tcpPort())); + .doOnSubscribe(subscription -> getLogger().info(format(RSOCKET_WS_COMMUNICATOR_STARTED_MESSAGE, configuration.host(), configuration.webSocketPort()))); + getLogger().info(format(RSOCKET_WS_COMMUNICATOR_CREATED_MESSAGE, configuration.host(), configuration.tcpPort())); return; } throw new RsocketClientException(format(UNSUPPORTED_TRANSPORT, configuration.transport())); diff --git a/application-rsocket/src/main/java/ru/art/rsocket/configuration/RsocketModuleConfiguration.java b/application-rsocket/src/main/java/ru/art/rsocket/configuration/RsocketModuleConfiguration.java index b9a857e0d..8ed008188 100644 --- a/application-rsocket/src/main/java/ru/art/rsocket/configuration/RsocketModuleConfiguration.java +++ b/application-rsocket/src/main/java/ru/art/rsocket/configuration/RsocketModuleConfiguration.java @@ -138,11 +138,11 @@ class RsocketModuleDefaultConfiguration implements RsocketModuleConfiguration { private final List> responseValueInterceptors = initializeValueInterceptors(); private List initializeInterceptors() { - return linkedListOf(new RsocketLoggingInterceptor(this::isEnableRawDataTracing)); + return linkedListOf(new RsocketLoggingInterceptor()); } private List> initializeValueInterceptors() { - return isEnableValueTracing() ? linkedListOf(new LoggingValueInterceptor<>()) : linkedListOf(); + return linkedListOf(new LoggingValueInterceptor<>(this::isEnableValueTracing)); } private final Map communicationTargets = mapOf(); diff --git a/application-rsocket/src/main/java/ru/art/rsocket/interceptor/RsocketLoggingInterceptor.java b/application-rsocket/src/main/java/ru/art/rsocket/interceptor/RsocketLoggingInterceptor.java index eaed908a0..8699d0023 100644 --- a/application-rsocket/src/main/java/ru/art/rsocket/interceptor/RsocketLoggingInterceptor.java +++ b/application-rsocket/src/main/java/ru/art/rsocket/interceptor/RsocketLoggingInterceptor.java @@ -27,17 +27,15 @@ import reactor.core.publisher.*; import reactor.util.annotation.NonNull; import static java.text.MessageFormat.*; +import static lombok.AccessLevel.*; import static reactor.core.publisher.Flux.*; -import static ru.art.core.extension.NullCheckingExtensions.*; import static ru.art.logging.LoggingModule.*; import static ru.art.rsocket.constants.RsocketModuleConstants.LoggingMessages.*; -import java.util.function.*; +import static ru.art.rsocket.module.RsocketModule.*; @RequiredArgsConstructor public class RsocketLoggingInterceptor implements RSocketInterceptor { - private final Supplier enableTracing; - @Getter(lazy = true) - private final boolean enableTracingResult = getOrElse(enableTracing.get(), false); + @Getter(lazy = true, value = PRIVATE) private final static Logger logger = loggingModule().getLogger(RSocketInterceptor.class); @Override @@ -45,59 +43,59 @@ public RSocket apply(RSocket rsocket) { return new RSocketProxy(rsocket) { @Override public Mono fireAndForget(@NonNull Payload payload) { - if (isEnableTracingResult()) { - logger.info(format(RSOCKET_FIRE_AND_FORGET_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8())); + if (rsocketModule().isEnableRawDataTracing()) { + getLogger().info(format(RSOCKET_FIRE_AND_FORGET_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8())); } - Mono result = super.fireAndForget(payload).doOnError(error -> logger.error(format(RSOCKET_FIRE_AND_FORGET_EXCEPTION_LOG, error))); - return isEnableTracingResult() - ? result.doOnSubscribe(nothing -> logger.info(RSOCKET_FIRE_AND_FORGET_RESPONSE_LOG)) + Mono result = super.fireAndForget(payload).doOnError(error -> getLogger().error(format(RSOCKET_FIRE_AND_FORGET_EXCEPTION_LOG, error))); + return rsocketModule().isEnableRawDataTracing() + ? result.doOnSubscribe(nothing -> getLogger().info(RSOCKET_FIRE_AND_FORGET_RESPONSE_LOG)) : result; } @Override public Mono requestResponse(@NonNull Payload payload) { - if (isEnableTracingResult()) { - logger.info(format(RSOCKET_REQUEST_RESPONSE_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8())); + if (rsocketModule().isEnableRawDataTracing()) { + getLogger().info(format(RSOCKET_REQUEST_RESPONSE_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8())); } - Mono result = super.requestResponse(payload).doOnError(error -> logger.error(format(RSOCKET_REQUEST_RESPONSE_EXCEPTION_LOG, error))); - return isEnableTracingResult() - ? result.doOnNext(response -> logger.info(format(RSOCKET_REQUEST_RESPONSE_RESPONSE_LOG, response.getDataUtf8(), response.getMetadataUtf8()))) + Mono result = super.requestResponse(payload).doOnError(error -> getLogger().error(format(RSOCKET_REQUEST_RESPONSE_EXCEPTION_LOG, error))); + return rsocketModule().isEnableRawDataTracing() + ? result.doOnNext(response -> getLogger().info(format(RSOCKET_REQUEST_RESPONSE_RESPONSE_LOG, response.getDataUtf8(), response.getMetadataUtf8()))) : result; } @Override public Flux requestStream(@NonNull Payload payload) { - if (isEnableTracingResult()) { - logger.info(format(RSOCKET_REQUEST_STREAM_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8())); + if (rsocketModule().isEnableRawDataTracing()) { + getLogger().info(format(RSOCKET_REQUEST_STREAM_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8())); } - Flux result = super.requestStream(payload).doOnError(error -> logger.error(format(RSOCKET_REQUEST_STREAM_EXCEPTION_LOG, error))); - return isEnableTracingResult() - ? result.doOnNext(response -> logger.info(format(RSOCKET_REQUEST_STREAM_RESPONSE_LOG, response.getDataUtf8(), response.getMetadataUtf8()))) + Flux result = super.requestStream(payload).doOnError(error -> getLogger().error(format(RSOCKET_REQUEST_STREAM_EXCEPTION_LOG, error))); + return rsocketModule().isEnableRawDataTracing() + ? result.doOnNext(response -> getLogger().info(format(RSOCKET_REQUEST_STREAM_RESPONSE_LOG, response.getDataUtf8(), response.getMetadataUtf8()))) : result; } @Override public Flux requestChannel(@NonNull Publisher payloads) { - if (isEnableTracingResult()) { + if (rsocketModule().isEnableRawDataTracing()) { payloads = from(payloads). - doOnNext(payload -> logger.info(format(RSOCKET_REQUEST_CHANNEL_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8()))); + doOnNext(payload -> getLogger().info(format(RSOCKET_REQUEST_CHANNEL_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8()))); } Flux result = super.requestChannel(from(payloads) - .doOnError(error -> logger.error(format(RSOCKET_REQUEST_CHANNEL_EXCEPTION_LOG, error)))); - return enableTracing.get() - ? result.doOnNext(payload -> logger.info(format(RSOCKET_REQUEST_CHANNEL_RESPONSE_LOG, payload.getDataUtf8(), payload.getMetadataUtf8()))) + .doOnError(error -> getLogger().error(format(RSOCKET_REQUEST_CHANNEL_EXCEPTION_LOG, error)))); + return rsocketModule().isEnableRawDataTracing() + ? result.doOnNext(payload -> getLogger().info(format(RSOCKET_REQUEST_CHANNEL_RESPONSE_LOG, payload.getDataUtf8(), payload.getMetadataUtf8()))) : result; } @Override public Mono metadataPush(@NonNull Payload payload) { - if (isEnableTracingResult()) { - logger.info(format(RSOCKET_METADATA_PUSH_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8())); + if (rsocketModule().isEnableRawDataTracing()) { + getLogger().info(format(RSOCKET_METADATA_PUSH_REQUEST_LOG, payload.getDataUtf8(), payload.getMetadataUtf8())); } - Mono result = super.metadataPush(payload).doOnError(error -> logger.error(format(RSOCKET_METADATA_PUSH_EXCEPTION_LOG, error))); - return isEnableTracingResult() - ? result.doOnSubscribe(nothing -> logger.info(RSOCKET_METADATA_PUSH_RESPONSE_LOG)) + Mono result = super.metadataPush(payload).doOnError(error -> getLogger().error(format(RSOCKET_METADATA_PUSH_EXCEPTION_LOG, error))); + return rsocketModule().isEnableRawDataTracing() + ? result.doOnSubscribe(nothing -> getLogger().info(RSOCKET_METADATA_PUSH_RESPONSE_LOG)) : result; } }; diff --git a/application-rsocket/src/main/java/ru/art/rsocket/model/RsocketRequestContext.java b/application-rsocket/src/main/java/ru/art/rsocket/model/RsocketRequestContext.java index 1125b7a29..284de40e6 100644 --- a/application-rsocket/src/main/java/ru/art/rsocket/model/RsocketRequestContext.java +++ b/application-rsocket/src/main/java/ru/art/rsocket/model/RsocketRequestContext.java @@ -20,6 +20,7 @@ import io.rsocket.*; import lombok.*; +import org.apache.logging.log4j.*; import ru.art.entity.Value; import ru.art.entity.*; import ru.art.entity.interceptor.*; @@ -29,6 +30,7 @@ import ru.art.service.model.*; import static java.text.MessageFormat.*; import static java.util.Objects.*; +import static lombok.AccessLevel.PRIVATE; import static reactor.core.publisher.Flux.*; import static ru.art.core.caster.Caster.*; import static ru.art.core.checker.CheckerForEmptiness.isEmpty; @@ -48,6 +50,8 @@ @Getter @Builder public class RsocketRequestContext { + @Getter(lazy = true, value = PRIVATE) + private static final Logger logger = loggingModule().getLogger(RsocketRequestContext.class); private final ServiceRequest request; private final RsocketReactiveMethods rsocketReactiveMethods; @Builder.Default @@ -62,7 +66,7 @@ public static RsocketRequestContext fromPayload(Payload payload, RsocketDataForm payload.release(payload.refCnt()); } catch (Throwable throwable) { if (rsocketModule().isEnableRawDataTracing()) { - loggingModule().getLogger(RsocketRequestContext.class).error(format(FAILED_TO_READ_PAYLOAD, throwable.getMessage(), throwable)); + getLogger().error(format(FAILED_TO_READ_PAYLOAD, throwable.getMessage(), throwable)); } return RsocketRequestContext.builder().stopHandling(true).build(); } diff --git a/application-rsocket/src/main/java/ru/art/rsocket/module/RsocketModule.java b/application-rsocket/src/main/java/ru/art/rsocket/module/RsocketModule.java index 44065b7c8..cab244a6a 100644 --- a/application-rsocket/src/main/java/ru/art/rsocket/module/RsocketModule.java +++ b/application-rsocket/src/main/java/ru/art/rsocket/module/RsocketModule.java @@ -18,32 +18,31 @@ package ru.art.rsocket.module; -import io.rsocket.RSocket; -import lombok.Getter; -import org.apache.logging.log4j.Logger; +import io.rsocket.*; +import lombok.*; +import org.apache.logging.log4j.*; import ru.art.core.module.Module; -import ru.art.rsocket.configuration.RsocketModuleConfiguration; -import ru.art.rsocket.server.RsocketServer; -import ru.art.rsocket.state.RsocketModuleState; -import static ru.art.core.context.Context.context; -import static ru.art.core.context.Context.contextIsNotReady; -import static ru.art.core.extension.NullCheckingExtensions.doIfNotNull; -import static ru.art.logging.LoggingModule.loggingModule; -import static ru.art.rsocket.configuration.RsocketModuleConfiguration.DEFAULT_CONFIGURATION; -import static ru.art.rsocket.configuration.RsocketModuleConfiguration.RsocketModuleDefaultConfiguration; -import static ru.art.rsocket.constants.RsocketModuleConstants.RSOCKET_CLIENT_DISPOSING; -import static ru.art.rsocket.constants.RsocketModuleConstants.RSOCKET_MODULE_ID; +import ru.art.rsocket.configuration.*; +import ru.art.rsocket.server.*; +import ru.art.rsocket.state.*; +import static lombok.AccessLevel.*; +import static ru.art.core.context.Context.*; +import static ru.art.core.extension.NullCheckingExtensions.*; +import static ru.art.logging.LoggingModule.*; +import static ru.art.rsocket.configuration.RsocketModuleConfiguration.*; +import static ru.art.rsocket.constants.RsocketModuleConstants.*; @Getter public class RsocketModule implements Module { - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private static final RsocketModuleConfiguration rsocketModule = context().getModule(RSOCKET_MODULE_ID, RsocketModule::new); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private static final RsocketModuleState rsocketModuleState = context().getModuleState(RSOCKET_MODULE_ID, RsocketModule::new); private final String id = RSOCKET_MODULE_ID; private final RsocketModuleConfiguration defaultConfiguration = RsocketModuleDefaultConfiguration.DEFAULT_CONFIGURATION; private final RsocketModuleState state = new RsocketModuleState(); - private static Logger logger = loggingModule().getLogger(RsocketModule.class); + @Getter(lazy = true, value = PRIVATE) + private static final Logger logger = loggingModule().getLogger(RsocketModule.class); public static RsocketModuleConfiguration rsocketModule() { if (contextIsNotReady()) { @@ -68,6 +67,6 @@ private void disposeRsocket(RSocket rsocket) { return; } rsocket.dispose(); - logger.info(RSOCKET_CLIENT_DISPOSING); + getLogger().info(RSOCKET_CLIENT_DISPOSING); } } diff --git a/application-rsocket/src/main/java/ru/art/rsocket/server/RsocketServer.java b/application-rsocket/src/main/java/ru/art/rsocket/server/RsocketServer.java index 1cac435e0..123218615 100644 --- a/application-rsocket/src/main/java/ru/art/rsocket/server/RsocketServer.java +++ b/application-rsocket/src/main/java/ru/art/rsocket/server/RsocketServer.java @@ -34,6 +34,7 @@ import static java.text.MessageFormat.*; import static java.time.Duration.*; import static java.util.Objects.*; +import static lombok.AccessLevel.*; import static reactor.core.publisher.Mono.*; import static ru.art.core.caster.Caster.*; import static ru.art.core.constants.NetworkConstants.*; @@ -52,7 +53,8 @@ public class RsocketServer { @Getter private final Mono serverChannel; private Disposable serverDisposable; - private final Logger logger = loggingModule().getLogger(RsocketServer.class); + @Getter(lazy = true, value = PRIVATE) + private final static Logger logger = loggingModule().getLogger(RsocketServer.class); private RsocketServer(RsocketTransport transport) { this.transport = transport; @@ -106,7 +108,7 @@ private Mono createServer() { .entrySet() .stream() .filter(entry -> entry.getValue().getServiceTypes().contains(RSOCKET_SERVICE_TYPE)) - .forEach(entry -> logger.info(format(RSOCKET_LOADED_SERVICE_MESSAGE, + .forEach(entry -> getLogger().info(format(RSOCKET_LOADED_SERVICE_MESSAGE, rsocketModule().getServerHost().equals(BROADCAST_IP_ADDRESS) ? contextConfiguration().getIpAddress() : rsocketModule().getServerHost(), @@ -139,11 +141,10 @@ public static RsocketServer startRsocketWebSocketServer() { public void subscribe() { final long timestamp = currentTimeMillis(); - serverDisposable = serverChannel.subscribe(serverChannel -> logger - .info(format(transport == TCP - ? RSOCKET_TCP_ACCEPTOR_STARTED_MESSAGE - : RSOCKET_WS_ACCEPTOR_STARTED_MESSAGE, - currentTimeMillis() - timestamp))); + serverDisposable = serverChannel.subscribe(serverChannel -> getLogger().info(format(transport == TCP + ? RSOCKET_TCP_ACCEPTOR_STARTED_MESSAGE + : RSOCKET_WS_ACCEPTOR_STARTED_MESSAGE, + currentTimeMillis() - timestamp))); } public void await() { @@ -161,9 +162,9 @@ public void restart() { serverDisposable.dispose(); } new RsocketServer(transport).subscribe(); - logger.info(format(RSOCKET_RESTARTING_MESSAGE, currentTimeMillis() - millis)); + getLogger().info(format(RSOCKET_RESTARTING_MESSAGE, currentTimeMillis() - millis)); } catch (Throwable throwable) { - logger.error(RSOCKET_RESTART_FAILED); + getLogger().error(RSOCKET_RESTART_FAILED); } } @@ -173,9 +174,9 @@ public void stop() { if (nonNull(serverDisposable)) { serverDisposable.dispose(); } - logger.info(format(RSOCKET_STOPPING_MESSAGE, currentTimeMillis() - millis)); + getLogger().info(format(RSOCKET_STOPPING_MESSAGE, currentTimeMillis() - millis)); } catch (Throwable throwable) { - logger.error(RSOCKET_STOP_FAILED); + getLogger().error(RSOCKET_STOP_FAILED); } } diff --git a/application-rsocket/src/main/java/ru/art/rsocket/writer/ServiceResponsePayloadWriter.java b/application-rsocket/src/main/java/ru/art/rsocket/writer/ServiceResponsePayloadWriter.java index 4e0e0eef8..cf93d3c55 100644 --- a/application-rsocket/src/main/java/ru/art/rsocket/writer/ServiceResponsePayloadWriter.java +++ b/application-rsocket/src/main/java/ru/art/rsocket/writer/ServiceResponsePayloadWriter.java @@ -85,10 +85,11 @@ public static Flux writeResponseReactive(RsocketReactiveMethods rsocket .getReactiveServiceExceptionWrappers() .entrySet() .stream() - .reduce(flux, (resultFlux, entry) -> resultFlux.onErrorResume(entry.getKey(), exception -> cast(just(writePayloadData(fromServiceResponse(responseMapper).map(cast(ServiceResponse.builder() - .command(serviceResponse.getCommand()) - .serviceException(entry.getValue().wrap(serviceResponse.getCommand(), cast(exception))) - .build())), dataFormat)))), (current, next) -> next) + .reduce(flux, (resultFlux, entry) -> resultFlux + .onErrorResume(entry.getKey(), exception -> cast(just(writePayloadData(fromServiceResponse(responseMapper).map(cast(ServiceResponse.builder() + .command(serviceResponse.getCommand()) + .serviceException(entry.getValue().wrap(serviceResponse.getCommand(), cast(exception))) + .build())), dataFormat)))), (current, next) -> next) .onErrorResume(Throwable.class, exception -> just(writePayloadData(fromServiceResponse(responseMapper).map(cast(ServiceResponse.builder() .command(serviceResponse.getCommand()) .serviceException(exceptionWrappers.getUndeclaredExceptionWrapper().wrap(serviceResponse.getCommand(), exception)) diff --git a/application-service/src/main/java/ru/art/service/ServiceLoggingInterception.java b/application-service/src/main/java/ru/art/service/ServiceLoggingInterception.java index 71a21be25..2aa647887 100644 --- a/application-service/src/main/java/ru/art/service/ServiceLoggingInterception.java +++ b/application-service/src/main/java/ru/art/service/ServiceLoggingInterception.java @@ -26,6 +26,7 @@ import ru.art.service.model.*; import static java.text.MessageFormat.*; import static java.util.Objects.*; +import static lombok.AccessLevel.PRIVATE; import static org.apache.logging.log4j.ThreadContext.*; import static ru.art.core.checker.CheckerForEmptiness.isEmpty; import static ru.art.core.constants.StringConstants.*; @@ -44,8 +45,8 @@ public class ServiceLoggingInterception implements ServiceRequestInterception, ServiceResponseInterception { private final static ThreadLocal> serviceLoggingParameters = new ThreadLocal<>(); - @Getter(lazy = true) - private final Logger logger = loggingModule().getLogger(ServiceLoggingInterception.class); + @Getter(lazy = true, value = PRIVATE) + private static final Logger logger = loggingModule().getLogger(ServiceLoggingInterception.class); private static void putRequestResponseMetrics(ServiceRequest request, ServiceCallLoggingParameters parameters) { putIfNotNull(REQUEST_KEY, request); diff --git a/application-state-api/src/main/java/ru/art/state/api/communication/grpc/LockServiceProxySpecification.java b/application-state-api/src/main/java/ru/art/state/api/communication/grpc/LockServiceProxySpecification.java index a530fa67d..e19bed4a1 100644 --- a/application-state-api/src/main/java/ru/art/state/api/communication/grpc/LockServiceProxySpecification.java +++ b/application-state-api/src/main/java/ru/art/state/api/communication/grpc/LockServiceProxySpecification.java @@ -23,6 +23,7 @@ import ru.art.grpc.client.communicator.*; import ru.art.grpc.client.specification.*; import ru.art.service.exception.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.caster.Caster.*; import static ru.art.grpc.client.communicator.GrpcCommunicator.*; import static ru.art.state.api.constants.StateApiConstants.LockServiceConstants.*; @@ -42,14 +43,14 @@ public LockServiceProxySpecification(String path, String host, Integer port) { this.port = port; } - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) @Accessors(fluent = true) private final GrpcCommunicator lock = grpcCommunicator(host, port, path) .serviceId(LOCK_SERVICE_ID) .methodId(LOCK) .requestMapper(fromLockRequest); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) @Accessors(fluent = true) private final GrpcCommunicator unlock = grpcCommunicator(host, port, path) .serviceId(LOCK_SERVICE_ID) diff --git a/application-state-api/src/main/java/ru/art/state/api/communication/grpc/NetworkServiceProxySpecification.java b/application-state-api/src/main/java/ru/art/state/api/communication/grpc/NetworkServiceProxySpecification.java index 180c2ebf4..a72018daf 100644 --- a/application-state-api/src/main/java/ru/art/state/api/communication/grpc/NetworkServiceProxySpecification.java +++ b/application-state-api/src/main/java/ru/art/state/api/communication/grpc/NetworkServiceProxySpecification.java @@ -23,6 +23,7 @@ import ru.art.grpc.client.communicator.*; import ru.art.grpc.client.specification.*; import ru.art.service.exception.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.caster.Caster.*; import static ru.art.entity.PrimitiveMapping.*; import static ru.art.grpc.client.communicator.GrpcCommunicator.*; @@ -40,7 +41,7 @@ public class NetworkServiceProxySpecification implements GrpcCommunicationSpecif private final String host; private final Integer port; - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) @Accessors(fluent = true) private final GrpcCommunicator getClusterProfile = grpcCommunicator(host, port, path) .serviceId(NETWORK_SERVICE_ID) @@ -48,28 +49,28 @@ public class NetworkServiceProxySpecification implements GrpcCommunicationSpecif .requestMapper(fromClusterProfileRequest) .responseMapper(toClusterProfileResponse); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) @Accessors(fluent = true) private final GrpcCommunicator connect = grpcCommunicator(host, port, path) .serviceId(NETWORK_SERVICE_ID) .requestMapper(fromModuleConnectionRequest) .methodId(CONNECT); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) @Accessors(fluent = true) private final GrpcCommunicator incrementSession = grpcCommunicator(host, port, path) .serviceId(NETWORK_SERVICE_ID) .methodId(INCREMENT_SESSION) .requestMapper(fromModuleConnectionRequest); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) @Accessors(fluent = true) private final GrpcCommunicator decrementSession = grpcCommunicator(host, port, path) .serviceId(NETWORK_SERVICE_ID) .methodId(DECREMENT_SESSION) .requestMapper(fromModuleConnectionRequest); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) @Accessors(fluent = true) private final GrpcCommunicator getSessions = grpcCommunicator(host, port, path) .serviceId(NETWORK_SERVICE_ID) diff --git a/application-state/src/main/java/ru/art/state/module/ApplicationStateModule.java b/application-state/src/main/java/ru/art/state/module/ApplicationStateModule.java index f386887a3..4c3eea968 100644 --- a/application-state/src/main/java/ru/art/state/module/ApplicationStateModule.java +++ b/application-state/src/main/java/ru/art/state/module/ApplicationStateModule.java @@ -28,6 +28,7 @@ import ru.art.state.service.*; import ru.art.state.specification.*; import static java.time.Duration.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.config.extensions.activator.AgileConfigurationsActivator.*; import static ru.art.core.context.Context.*; import static ru.art.grpc.server.GrpcServer.*; @@ -42,9 +43,9 @@ @Getter public class ApplicationStateModule implements Module { - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private final static ApplicationStateModuleConfiguration applicationStateModule = context().getModule(APPLICATION_STATE_MODULE_ID, ApplicationStateModule::new); - @Getter(lazy = true) + @Getter(lazy = true, value = PRIVATE) private final static ApplicationState applicationState = context().getModuleState(APPLICATION_STATE_MODULE_ID, ApplicationStateModule::new); private final String id = APPLICATION_STATE_MODULE_ID; private final ApplicationStateModuleConfiguration defaultConfiguration = new ApplicationStateModuleDefaultConfiguration(); diff --git a/application-tarantool/src/main/java/ru/art/tarantool/configuration/TarantoolConnectionConfiguration.java b/application-tarantool/src/main/java/ru/art/tarantool/configuration/TarantoolConnectionConfiguration.java index 9ba4ca76c..06870ecda 100644 --- a/application-tarantool/src/main/java/ru/art/tarantool/configuration/TarantoolConnectionConfiguration.java +++ b/application-tarantool/src/main/java/ru/art/tarantool/configuration/TarantoolConnectionConfiguration.java @@ -33,5 +33,7 @@ public class TarantoolConnectionConfiguration { private final String username = DEFAULT_TARANTOOL_USERNAME; @Builder.Default private final int operationTimeoutMillis = DEFAULT_TARANTOOL_OPERATION_TIMEOUT; + @Builder.Default + private final int maxRetryCount = DEFAULT_TARANTOOL_RETRIES; private String password; } diff --git a/application-tarantool/src/main/java/ru/art/tarantool/connector/TarantoolConnector.java b/application-tarantool/src/main/java/ru/art/tarantool/connector/TarantoolConnector.java index b5c7e40ee..3d9a22771 100644 --- a/application-tarantool/src/main/java/ru/art/tarantool/connector/TarantoolConnector.java +++ b/application-tarantool/src/main/java/ru/art/tarantool/connector/TarantoolConnector.java @@ -18,13 +18,16 @@ package ru.art.tarantool.connector; +import lombok.*; import lombok.experimental.*; +import org.apache.logging.log4j.*; import org.tarantool.*; import ru.art.tarantool.configuration.*; import ru.art.tarantool.exception.*; import ru.art.tarantool.initializer.*; import static java.text.MessageFormat.*; import static java.util.Objects.*; +import static lombok.AccessLevel.PRIVATE; import static ru.art.core.checker.CheckerForEmptiness.isEmpty; import static ru.art.core.constants.StringConstants.*; import static ru.art.logging.LoggingModule.*; @@ -40,6 +43,9 @@ @UtilityClass public final class TarantoolConnector { + @Getter(lazy = true, value = PRIVATE) + private static final Logger logger = loggingModule().getLogger(TarantoolConnector.class); + public static TarantoolClient connectToTarantoolInstance(String instanceId) { int retries = 0; TarantoolConfiguration tarantoolConfiguration = getTarantoolConfiguration(instanceId, tarantoolModule().getTarantoolConfigurations()); @@ -51,17 +57,17 @@ public static TarantoolClient connectToTarantoolInstance(String instanceId) { config.operationExpiryTimeMillis = connectionConfiguration.getOperationTimeoutMillis(); String address = connectionConfiguration.getHost() + COLON + connectionConfiguration.getPort(); SocketChannelProvider socketChannelProvider = new RoundRobinSocketProviderImpl(address); - while (retries < DEFAULT_TARANTOOL_RETRIES) { + while (retries < connectionConfiguration.getMaxRetryCount()) { try { - loggingModule().getLogger(TarantoolConnector.class).info(format(WAITING_FOR_CONNECT, + getLogger().info(format(WAITING_FOR_CONNECT, instanceId, address, config.initTimeoutMillis)); TarantoolClientImpl client = new TarantoolClientImpl(socketChannelProvider, config); - loggingModule().getLogger(TarantoolInitializer.class).info(format(TARANTOOL_SUCCESSFULLY_CONNECTED, instanceId, address)); + getLogger().info(format(TARANTOOL_SUCCESSFULLY_CONNECTED, instanceId, address)); return client; } catch (CommunicationException exception) { - loggingModule().getLogger(TarantoolConnector.class).warn(format(UNABLE_TO_CONNECT_TO_TARANTOOL_RETRY, instanceId, address), exception); + getLogger().warn(format(UNABLE_TO_CONNECT_TO_TARANTOOL_RETRY, instanceId, address), exception); } catch (Throwable throwable) { throw new TarantoolConnectionException(format(UNABLE_TO_CONNECT_TO_TARANTOOL, instanceId, address), throwable); } @@ -89,17 +95,17 @@ public static TarantoolClient connectToTarantoolCluster(String instanceId) { .map(configuration -> configuration.getHost() + COLON + configuration.getPort()) .toArray(String[]::new); SocketChannelProvider socketChannelProvider = new RoundRobinSocketProviderImpl(addresses); - while (retries < DEFAULT_TARANTOOL_RETRIES) { + while (retries < connectionConfiguration.getMaxRetryCount()) { try { - loggingModule().getLogger(TarantoolConnector.class).info(format(WAITING_FOR_CONNECT, + getLogger().info(format(WAITING_FOR_CONNECT, instanceId, Arrays.toString(addresses), config.initTimeoutMillis)); TarantoolClientImpl client = new TarantoolClientImpl(socketChannelProvider, config); - loggingModule().getLogger(TarantoolInitializer.class).info(format(TARANTOOL_SUCCESSFULLY_CONNECTED, instanceId, Arrays.toString(addresses))); + getLogger().info(format(TARANTOOL_SUCCESSFULLY_CONNECTED, instanceId, Arrays.toString(addresses))); return client; } catch (CommunicationException exception) { - loggingModule().getLogger(TarantoolConnector.class).warn(format(UNABLE_TO_CONNECT_TO_TARANTOOL_RETRY, instanceId, Arrays.toString(addresses)), exception); + getLogger().warn(format(UNABLE_TO_CONNECT_TO_TARANTOOL_RETRY, instanceId, Arrays.toString(addresses)), exception); } catch (Throwable throwable) { throw new TarantoolConnectionException(format(UNABLE_TO_CONNECT_TO_TARANTOOL, instanceId, Arrays.toString(addresses)), throwable); } @@ -121,7 +127,7 @@ public static TarantoolClient tryConnectToTarantool(String instanceId) { SocketChannelProvider socketChannelProvider = new RoundRobinSocketProviderImpl(address); TarantoolClientImpl tarantoolClient; try { - loggingModule().getLogger(TarantoolConnector.class).info(format(TRYING_TO_CONNECT, + getLogger().info(format(TRYING_TO_CONNECT, instanceId, address, config.initTimeoutMillis)); diff --git a/application-tarantool/src/main/java/ru/art/tarantool/executor/TarantoolLuaExecutor.java b/application-tarantool/src/main/java/ru/art/tarantool/executor/TarantoolLuaExecutor.java index fd4ab7d94..01e889d5d 100644 --- a/application-tarantool/src/main/java/ru/art/tarantool/executor/TarantoolLuaExecutor.java +++ b/application-tarantool/src/main/java/ru/art/tarantool/executor/TarantoolLuaExecutor.java @@ -18,10 +18,13 @@ package ru.art.tarantool.executor; +import lombok.*; import lombok.experimental.*; +import org.apache.logging.log4j.*; import ru.art.core.extension.*; import static java.text.MessageFormat.*; import static java.util.Objects.*; +import static lombok.AccessLevel.*; import static ru.art.logging.LoggingModule.*; import static ru.art.tarantool.constants.TarantoolModuleConstants.LoggingMessages.*; import static ru.art.tarantool.module.TarantoolModule.*; @@ -29,6 +32,9 @@ @UtilityClass public final class TarantoolLuaExecutor { + @Getter(lazy = true, value = PRIVATE) + private static final Logger logger = loggingModule().getLogger(TarantoolLuaExecutor.class); + public static void executeLuaScript(String instanceId, String scriptName) { String script; InputStream scriptStream = TarantoolLuaExecutor.class @@ -43,7 +49,7 @@ public static void executeLuaScript(String instanceId, String scriptName) { public static void evaluateLuaScript(String instanceId, String script) { if (tarantoolModule().isEnableTracing()) { - loggingModule().getLogger(TarantoolLuaExecutor.class).trace(format(EVALUATING_LUA_SCRIPT, script)); + getLogger().trace(format(EVALUATING_LUA_SCRIPT, script)); } tarantoolModuleState().getClient(instanceId).syncOps().eval(script); } diff --git a/application-tarantool/src/main/java/ru/art/tarantool/initializer/TarantoolInitializer.java b/application-tarantool/src/main/java/ru/art/tarantool/initializer/TarantoolInitializer.java index 4feb734be..9b6720f2f 100644 --- a/application-tarantool/src/main/java/ru/art/tarantool/initializer/TarantoolInitializer.java +++ b/application-tarantool/src/main/java/ru/art/tarantool/initializer/TarantoolInitializer.java @@ -20,24 +20,25 @@ import com.mitchellbosecke.pebble.*; import com.mitchellbosecke.pebble.loader.*; -import org.apache.logging.log4j.*; +import lombok.*; +import org.apache.logging.log4j.Logger; import org.tarantool.*; import org.zeroturnaround.exec.*; -import ru.art.core.determinant.SystemDeterminant; import ru.art.tarantool.configuration.*; import ru.art.tarantool.exception.*; import ru.art.tarantool.module.*; import static java.io.File.*; -import static java.lang.System.currentTimeMillis; +import static java.lang.System.*; import static java.lang.Thread.*; import static java.nio.file.Files.*; import static java.nio.file.Paths.*; import static java.text.MessageFormat.*; import static java.util.Objects.*; -import static java.util.Optional.ofNullable; +import static java.util.Optional.*; import static java.util.concurrent.ForkJoinPool.*; -import static java.util.concurrent.TimeUnit.MILLISECONDS; -import static java.util.stream.Collectors.toSet; +import static java.util.concurrent.TimeUnit.*; +import static java.util.stream.Collectors.*; +import static lombok.AccessLevel.*; import static org.apache.logging.log4j.io.IoBuilder.*; import static ru.art.core.caster.Caster.*; import static ru.art.core.checker.CheckerForEmptiness.*; @@ -48,13 +49,12 @@ import static ru.art.core.extension.FileExtensions.*; import static ru.art.core.factory.CollectionsFactory.*; import static ru.art.core.jar.JarExtensions.*; -import static ru.art.core.wrapper.ExceptionWrapper.ignoreException; -import static ru.art.core.wrapper.ExceptionWrapper.wrapException; +import static ru.art.core.wrapper.ExceptionWrapper.*; import static ru.art.logging.LoggingModule.*; import static ru.art.tarantool.connector.TarantoolConnector.*; +import static ru.art.tarantool.constants.TarantoolModuleConstants.*; import static ru.art.tarantool.constants.TarantoolModuleConstants.Directories.*; import static ru.art.tarantool.constants.TarantoolModuleConstants.ExceptionMessages.*; -import static ru.art.tarantool.constants.TarantoolModuleConstants.*; import static ru.art.tarantool.constants.TarantoolModuleConstants.LoggingMessages.UNABLE_TO_CONNECT_TO_TARANTOOL; import static ru.art.tarantool.constants.TarantoolModuleConstants.LoggingMessages.*; import static ru.art.tarantool.constants.TarantoolModuleConstants.Scripts.*; @@ -67,13 +67,14 @@ import java.net.*; import java.nio.file.*; import java.util.*; -import java.util.concurrent.ForkJoinTask; +import java.util.concurrent.*; public class TarantoolInitializer { private final static OutputStream TARANTOOL_INITIALIZER_LOGGER_OUTPUT_STREAM = forLogger(loggingModule() .getLogger(TarantoolInitializer.class)) .buildOutputStream(); - private final static Logger logger = loggingModule().getLogger(TarantoolInitializer.class); + @Getter(lazy = true, value = PRIVATE) + private static final Logger logger = loggingModule().getLogger(TarantoolInitializer.class); public static void initializeTarantools() { tarantoolModule().getTarantoolConfigurations() @@ -106,7 +107,7 @@ private static void waitInitializationTask(String instanceId, TarantoolConfigura task.get(tarantoolModule().getLocalConfiguration().getProcessStartupTimeoutMillis(), MILLISECONDS); break; case REMOTE: - task.get(tarantoolModule().getProbeConnectionTimeoutMillis(), MILLISECONDS); + task.get(tarantoolModule().getConnectionTimeoutMillis(), MILLISECONDS); break; } } catch (Throwable throwable) { @@ -127,14 +128,14 @@ private static void initialTarantoolSynchronously(String instanceId, TarantoolCo } } catch (Throwable throwable) { if (instanceMode == LOCAL) { - logger.warn(format(UNABLE_TO_CONNECT_TO_TARANTOOL_ON_STARTUP, instanceId, address)); + getLogger().warn(format(UNABLE_TO_CONNECT_TO_TARANTOOL_ON_STARTUP, instanceId, address)); startTarantool(instanceId); return; } throw throwable; } if (instanceMode == LOCAL) { - logger.warn(format(UNABLE_TO_CONNECT_TO_TARANTOOL_ON_STARTUP, instanceId, address)); + getLogger().warn(format(UNABLE_TO_CONNECT_TO_TARANTOOL_ON_STARTUP, instanceId, address)); startTarantool(instanceId); } } @@ -167,7 +168,7 @@ private static void startTarantool(String instanceId) { String luaConfiguration = configuration.getInitialConfiguration().toLua(connectionConfiguration.getPort(), replicas); Path luaConfigurationPath = get(getLuaScriptPath(instanceId, localConfiguration, CONFIGURATION)); writeFile(luaConfigurationPath, luaConfiguration); - logger.info(format(WRITING_TARANTOOL_CONFIGURATION, instanceId, + getLogger().info(format(WRITING_TARANTOOL_CONFIGURATION, instanceId, address, luaConfigurationPath.toAbsolutePath())); StringWriter templateWriter = new StringWriter(); @@ -184,7 +185,7 @@ private static void startTarantool(String instanceId) { String luaUserConfiguration = templateWriter.toString(); Path userConfigurationPath = get(getLuaScriptPath(instanceId, localConfiguration, USER)); writeFile(userConfigurationPath, luaUserConfiguration); - logger.info(format(WRITING_TARANTOOL_USER_CONFIGURATION, + getLogger().info(format(WRITING_TARANTOOL_USER_CONFIGURATION, instanceId, address, userConfigurationPath.toAbsolutePath())); @@ -200,7 +201,7 @@ private static void startTarantool(String instanceId) { startTarantoolOutOfJar(instanceId, localConfiguration, address); } catch (Throwable throwable) { - logger.error(format(STARTUP_ERROR, instanceId), throwable); + getLogger().error(format(STARTUP_ERROR, instanceId), throwable); throw new TarantoolInitializationException(throwable); } } @@ -215,12 +216,12 @@ private static void startTarantoolFromJar(String instanceId, TarantoolLocalConfi createDirectories(get(executableDirectory)); extractCurrentJarEntry(TarantoolModule.class, localConfiguration.getExecutable(), executableDirectory); } - logger.info(format(EXTRACT_TARANTOOL_LUA_SCRIPTS, instanceId, address, luaDirectory)); + getLogger().info(format(EXTRACT_TARANTOOL_LUA_SCRIPTS, instanceId, address, luaDirectory)); String executableLogMessage = isEmpty(executableFilePath) || !isMac() ? EXTRACT_TARANTOOL_BINARY : USING_TARANTOOL_BINARY; - logger.info(format(executableLogMessage, instanceId, address, executableDirectory)); + getLogger().info(format(executableLogMessage, instanceId, address, executableDirectory)); String executableFile = isEmpty(executableFilePath) || !isMac() ? executableDirectory + separator + localConfiguration.getExecutable() : executableFilePath; if (!new File(executableFile).setExecutable(true)) { - logger.warn(format(FAILED_SET_EXECUTABLE, executableFile)); + getLogger().warn(format(FAILED_SET_EXECUTABLE, executableFile)); } List executableCommand = isWindows() ? dynamicArrayOf(WSL, convertToWslPath(executableFile)) @@ -248,7 +249,7 @@ private static void startTarantoolOutOfJar(String instanceId, TarantoolLocalConf throw new TarantoolInitializationException(format(TARANTOOL_EXECUTABLE_NOT_EXISTS, address, localConfiguration.getExecutable())); } if (!new File(executableUrl.getPath()).setExecutable(true)) { - logger.warn(format(FAILED_SET_EXECUTABLE, executableUrl.getPath())); + getLogger().warn(format(FAILED_SET_EXECUTABLE, executableUrl.getPath())); } List executableCommand; executableCommand = isWindows() @@ -279,13 +280,13 @@ private static void waitForTarantoolProcess(String instanceId, TarantoolLocalCon int checkIntervalMillis = localConfiguration.getProcessStartupCheckIntervalMillis(); int startupTimeoutMillis = localConfiguration.getProcessStartupTimeoutMillis(); while (!process.getProcess().isAlive()) { - logger.info(format(WAITING_FOR_INITIALIZATION, instanceId, address, startupTimeoutMillis, checkIntervalMillis)); + getLogger().info(format(WAITING_FOR_INITIALIZATION, instanceId, address, startupTimeoutMillis, checkIntervalMillis)); ignoreException(() -> sleep(checkIntervalMillis)); if (currentTimeMillis() - current > startupTimeoutMillis) { throw new TarantoolInitializationException(format(TARANTOOL_PROCESS_FAILED, instanceId)); } } ignoreException(() -> sleep(checkIntervalMillis)); - logger.info(format(TARANTOOL_PROCESS_SUCCESSFULLY_STARTED, instanceId, address)); + getLogger().info(format(TARANTOOL_PROCESS_SUCCESSFULLY_STARTED, instanceId, address)); } } diff --git a/application-tarantool/src/main/java/ru/art/tarantool/module/TarantoolModule.java b/application-tarantool/src/main/java/ru/art/tarantool/module/TarantoolModule.java index 5a9cc9852..c93f6361c 100644 --- a/application-tarantool/src/main/java/ru/art/tarantool/module/TarantoolModule.java +++ b/application-tarantool/src/main/java/ru/art/tarantool/module/TarantoolModule.java @@ -48,6 +48,7 @@ public class TarantoolModule implements Module entry) { - logger.info(format(CLOSING_TARANTOOL_CLIENT, entry.getKey())); + getLogger().info(format(CLOSING_TARANTOOL_CLIENT, entry.getKey())); ignoreException(entry.getValue()::close); } } From 79bf8728d2d936f28c502ee20f20c256f5b45fe2 Mon Sep 17 00:00:00 2001 From: anton Date: Wed, 25 Mar 2020 03:23:43 +0300 Subject: [PATCH 2/6] remove PublicApi.java added Test for Context & Modules --- .../config/extensions/ConfigExtensions.java | 2 - .../AgileConfigurationsActivator.java | 2 - .../extensions/grpc/GrpcConfigProvider.java | 2 - .../extensions/http/HttpConfigProvider.java | 2 - .../extensions/kafka/KafkaConfigProvider.java | 2 - .../logging/LoggingConfigProvider.java | 2 - .../metrics/MetricsConfigProvider.java | 2 - .../network/NetworkManagerConfigProvider.java | 2 - .../rocks/RocksDbConfigProvider.java | 2 - .../rsocket/RsocketConfigProvider.java | 2 - .../service/ServiceConfigProvider.java | 2 - .../extensions/sql/SqlConfigProvider.java | 2 - .../tarantool/TarantoolConfigProvider.java | 2 - .../java/ru/art/config/ConfigProvider.java | 2 - .../ru/art/core/annotation/PublicApi.java | 28 ----- .../core/configurator/ModuleConfigurator.java | 2 +- .../art/core/constants/LoggingMessages.java | 5 +- .../java/ru/art/core/context/Context.java | 37 +++++-- .../ConfigurationSpecification.groovy | 7 +- .../core/ModulesLoadingSpecification.groovy | 100 ++++++++++++++++++ .../test/specification/core/TestModule.java | 64 +++++++++++ ...tModuleAccessingDefaultsConfiguration.java | 15 +++ .../core/TestModuleOverrideConfiguration.java | 9 ++ .../rsocket/RsocketSpecification.groovy | 17 ++- .../src/test/resources/module-config.yml | 2 + 25 files changed, 236 insertions(+), 78 deletions(-) delete mode 100644 application-core/src/main/java/ru/art/core/annotation/PublicApi.java create mode 100644 application-test/src/test/groovy/ru/art/test/specification/core/ModulesLoadingSpecification.groovy create mode 100644 application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java create mode 100644 application-test/src/test/groovy/ru/art/test/specification/core/TestModuleAccessingDefaultsConfiguration.java create mode 100644 application-test/src/test/groovy/ru/art/test/specification/core/TestModuleOverrideConfiguration.java diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/ConfigExtensions.java b/application-config-extensions/src/main/java/ru/art/config/extensions/ConfigExtensions.java index bdff7e520..6003adf93 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/ConfigExtensions.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/ConfigExtensions.java @@ -21,7 +21,6 @@ import lombok.experimental.*; import ru.art.config.*; import ru.art.config.exception.*; -import ru.art.core.annotation.*; import static java.util.Collections.*; import static java.util.Objects.isNull; import static java.util.function.Function.*; @@ -36,7 +35,6 @@ import java.util.*; import java.util.function.*; -@PublicApi @UtilityClass public class ConfigExtensions { public static String configString(String sectionId, String path) { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/activator/AgileConfigurationsActivator.java b/application-config-extensions/src/main/java/ru/art/config/extensions/activator/AgileConfigurationsActivator.java index c6be2b49e..3fb756cc0 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/activator/AgileConfigurationsActivator.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/activator/AgileConfigurationsActivator.java @@ -21,7 +21,6 @@ import lombok.experimental.*; import org.apache.logging.log4j.*; import ru.art.config.extensions.provider.*; -import ru.art.core.annotation.*; import ru.art.core.configuration.ContextInitialConfiguration.*; import ru.art.core.context.*; import static java.text.MessageFormat.*; @@ -34,7 +33,6 @@ import static ru.art.core.context.Context.*; import static ru.art.logging.LoggingModule.*; -@PublicApi @UtilityClass public class AgileConfigurationsActivator { public static Context useAgileConfigurations(String mainModuleId) { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/grpc/GrpcConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/grpc/GrpcConfigProvider.java index 22b910e6b..dc7a147a2 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/grpc/GrpcConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/grpc/GrpcConfigProvider.java @@ -19,11 +19,9 @@ package ru.art.config.extensions.grpc; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.grpc.GrpcConfigKeys.*; -@PublicApi public class GrpcConfigProvider { public static Config grpcServerConfig() { return configInner(GRPC_SERVER_CONFIG_SECTION_ID); diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/http/HttpConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/http/HttpConfigProvider.java index 92a54c74f..be04b2e87 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/http/HttpConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/http/HttpConfigProvider.java @@ -20,11 +20,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.http.HttpConfigKeys.*; -@PublicApi @UtilityClass public class HttpConfigProvider { public static Config httpServerConfig() { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/kafka/KafkaConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/kafka/KafkaConfigProvider.java index aa64f042a..037459f48 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/kafka/KafkaConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/kafka/KafkaConfigProvider.java @@ -18,11 +18,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.kafka.KafkaConfigKeys.*; -@PublicApi @UtilityClass public class KafkaConfigProvider { public static Config kafkaBrokerConfig() { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/logging/LoggingConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/logging/LoggingConfigProvider.java index f8cab36e3..51fbef0db 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/logging/LoggingConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/logging/LoggingConfigProvider.java @@ -20,11 +20,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.logging.LoggingConfigKeys.*; -@PublicApi @UtilityClass public class LoggingConfigProvider { public static Config loggingConfig() { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/metrics/MetricsConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/metrics/MetricsConfigProvider.java index e2f0f8ece..953af96a3 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/metrics/MetricsConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/metrics/MetricsConfigProvider.java @@ -20,11 +20,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.metrics.MetricsConfigKeys.*; -@PublicApi @UtilityClass public class MetricsConfigProvider { public static Config metricsConfig() { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/network/NetworkManagerConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/network/NetworkManagerConfigProvider.java index 176b77adc..33a83f3f5 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/network/NetworkManagerConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/network/NetworkManagerConfigProvider.java @@ -20,11 +20,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.network.NetworkManagerConfigKeys.*; -@PublicApi @UtilityClass public class NetworkManagerConfigProvider { public static Config networkManagerConfig() { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/rocks/RocksDbConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/rocks/RocksDbConfigProvider.java index 07a52a471..93064acf6 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/rocks/RocksDbConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/rocks/RocksDbConfigProvider.java @@ -20,11 +20,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.rocks.RocksDbConfigKeys.*; -@PublicApi @UtilityClass public class RocksDbConfigProvider { public static Config rocksDbConfig() { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/rsocket/RsocketConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/rsocket/RsocketConfigProvider.java index 042888628..2fab80b6d 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/rsocket/RsocketConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/rsocket/RsocketConfigProvider.java @@ -20,11 +20,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.rsocket.RsocketConfigKeys.*; -@PublicApi @UtilityClass public class RsocketConfigProvider { public static Config rsocketConfig() { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/service/ServiceConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/service/ServiceConfigProvider.java index 349638fa9..f0f903443 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/service/ServiceConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/service/ServiceConfigProvider.java @@ -24,7 +24,6 @@ import io.github.resilience4j.retry.*; import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import ru.art.service.model.*; import static io.github.resilience4j.bulkhead.BulkheadConfig.*; import static io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.*; @@ -37,7 +36,6 @@ import static ru.art.core.extension.ExceptionExtensions.*; import java.util.*; -@PublicApi @UtilityClass public class ServiceConfigProvider { public static CircuitBreakerServiceConfig getCircuitBreakerServiceConfig(String sectionId) { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/sql/SqlConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/sql/SqlConfigProvider.java index 4581e62f0..db7fddfc1 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/sql/SqlConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/sql/SqlConfigProvider.java @@ -20,11 +20,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.sql.SqlConfigKeys.*; -@PublicApi @UtilityClass public class SqlConfigProvider { public static Config sqlDbConfig() { diff --git a/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolConfigProvider.java b/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolConfigProvider.java index 2a88556e5..14c147f1e 100644 --- a/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolConfigProvider.java +++ b/application-config-extensions/src/main/java/ru/art/config/extensions/tarantool/TarantoolConfigProvider.java @@ -20,11 +20,9 @@ import lombok.experimental.*; import ru.art.config.*; -import ru.art.core.annotation.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.config.extensions.sql.SqlConfigKeys.*; -@PublicApi @UtilityClass public class TarantoolConfigProvider { public static Config tarantoolConfig() { diff --git a/application-config/src/main/java/ru/art/config/ConfigProvider.java b/application-config/src/main/java/ru/art/config/ConfigProvider.java index 715f8ea4d..c496fe0dc 100644 --- a/application-config/src/main/java/ru/art/config/ConfigProvider.java +++ b/application-config/src/main/java/ru/art/config/ConfigProvider.java @@ -22,14 +22,12 @@ import ru.art.config.cache.*; import ru.art.config.constants.*; import ru.art.config.exception.*; -import ru.art.core.annotation.*; import static java.util.Objects.*; import static ru.art.config.ConfigLoader.*; import static ru.art.config.constants.ConfigExceptionMessages.*; import static ru.art.config.constants.ConfigModuleConstants.*; import static ru.art.config.module.ConfigModule.*; -@PublicApi @UtilityClass public class ConfigProvider { private static final ConfigCacheContainer CONFIG_CACHE_CONTAINER = new ConfigCacheContainer(); diff --git a/application-core/src/main/java/ru/art/core/annotation/PublicApi.java b/application-core/src/main/java/ru/art/core/annotation/PublicApi.java deleted file mode 100644 index ba43de2af..000000000 --- a/application-core/src/main/java/ru/art/core/annotation/PublicApi.java +++ /dev/null @@ -1,28 +0,0 @@ -/* - * ART Java - * - * Copyright 2019 ART - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package ru.art.core.annotation; - -import static java.lang.annotation.RetentionPolicy.*; -import java.lang.annotation.*; - -@Documented -@Target(ElementType.TYPE) -@Retention(SOURCE) -public @interface PublicApi { -} diff --git a/application-core/src/main/java/ru/art/core/configurator/ModuleConfigurator.java b/application-core/src/main/java/ru/art/core/configurator/ModuleConfigurator.java index 97df3ee5a..e155f9468 100644 --- a/application-core/src/main/java/ru/art/core/configurator/ModuleConfigurator.java +++ b/application-core/src/main/java/ru/art/core/configurator/ModuleConfigurator.java @@ -23,5 +23,5 @@ @FunctionalInterface public interface ModuleConfigurator { - ModuleConfiguration configure(Module module); + C configure(Module module); } diff --git a/application-core/src/main/java/ru/art/core/constants/LoggingMessages.java b/application-core/src/main/java/ru/art/core/constants/LoggingMessages.java index fb8160791..3fd51dd15 100644 --- a/application-core/src/main/java/ru/art/core/constants/LoggingMessages.java +++ b/application-core/src/main/java/ru/art/core/constants/LoggingMessages.java @@ -21,8 +21,9 @@ import static ru.art.core.colorizer.AnsiColorizer.*; public interface LoggingMessages { - String CONTEXT_RELOADED_MESSAGE = success("Context was reloaded in {0}[ms]"); - String MODULE_LOADED_MESSAGE = success("Module: ''{0}'' was loaded in {1}[ms]"); + String CONTEXT_RELOADED_MESSAGE = success("Context has been reloaded in {0}[ms]"); + String CONTEXT_CHANGED = success("Context has been changed. New configuration class is {0}"); + String MODULE_LOADED_MESSAGE = success("Module: ''{0}'' was loaded in {1}[ms] with configuration class {2}"); String MODULE_OVERRIDDEN_MESSAGE = success("Module: ''{0}'' was overridden in {1}[ms]"); String MODULE_RELOADED_MESSAGE = success("Module: ''{0}'' was reloaded in {1}[ms]"); String MODULE_REFRESHED_MESSAGE = success("Module: ''{0}'' was refreshed in {1}[ms]"); diff --git a/application-core/src/main/java/ru/art/core/context/Context.java b/application-core/src/main/java/ru/art/core/context/Context.java index 59431bf23..add2ec216 100644 --- a/application-core/src/main/java/ru/art/core/context/Context.java +++ b/application-core/src/main/java/ru/art/core/context/Context.java @@ -49,13 +49,23 @@ public class Context { private volatile Long lastActionTimestamp = currentTimeMillis(); private Map> modules = concurrentHashMap(); + static { + out.println(ART_BANNER); + } + private Context() { + if (nonNull(INSTANCE)) { + out.println(format(CONTEXT_CHANGED, initialConfiguration.getClass().getName())); + } if (initialConfiguration.isUnloadModulesOnShutdown()) { getRuntime().addShutdownHook(new Thread(this::unloadModules)); } } private Context(ContextInitialConfiguration initialConfiguration) { + if (nonNull(INSTANCE)) { + out.println(format(CONTEXT_CHANGED, initialConfiguration.getClass().getName())); + } this.initialConfiguration = initialConfiguration; if (initialConfiguration.isUnloadModulesOnShutdown()) { getRuntime().addShutdownHook(new Thread(this::unloadModules)); @@ -63,6 +73,9 @@ private Context(ContextInitialConfiguration initialConfiguration) { } private Context(ContextInitialConfiguration contextInitialConfiguration, Map> modules) { + if (nonNull(INSTANCE)) { + out.println(format(CONTEXT_CHANGED, contextInitialConfiguration.getClass().getName())); + } this.initialConfiguration = contextInitialConfiguration; this.modules = modules; if (initialConfiguration.isUnloadModulesOnShutdown()) { @@ -76,7 +89,6 @@ public static Context initContext(ContextInitialConfiguration contextInitialConf ReentrantLock lock = Context.LOCK; lock.lock(); INSTANCE = new Context(contextInitialConfiguration); - out.println(ART_BANNER); lock.unlock(); return INSTANCE; } @@ -116,7 +128,7 @@ public static ContextInitialConfiguration contextConfiguration() { public C getModule(String moduleId, Module toLoadIfNotExists) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); - if (state != READY) { + if (isNull(INSTANCE) || state != READY) { return toLoadIfNotExists.getDefaultConfiguration(); } ModuleContainer moduleContainer = modules.get(moduleId); @@ -134,7 +146,7 @@ public C getModule(String public S getModuleState(String moduleId, Module toLoadIfNotExists) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); - if (state == LOADING_MODULES) { + if (isNull(INSTANCE) || state == LOADING_MODULES) { return toLoadIfNotExists.getState(); } ModuleContainer moduleContainer = modules.get(moduleId); @@ -152,7 +164,7 @@ public S getModuleState(S public C getModule(String moduleId, Supplier> toLoadIfNotExists) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); - if (state != READY) { + if (isNull(INSTANCE) || state != READY) { return toLoadIfNotExists.get().getDefaultConfiguration(); } ModuleContainer moduleContainer = modules.get(moduleId); @@ -171,7 +183,7 @@ public C getModule(String public S getModuleState(String moduleId, Supplier> toLoadIfNotExists) { if (isNull(moduleId)) throw new ContextInitializationException(MODULE_ID_IS_NULL); - if (state == LOADING_MODULES) { + if (isNull(INSTANCE) || state == LOADING_MODULES) { return toLoadIfNotExists.get().getState(); } ModuleContainer moduleContainer = modules.get(moduleId); @@ -192,8 +204,9 @@ public Context loadModule if (isNull(module)) throw new ContextInitializationException(MODULE_ID_IS_NULL); ContextState currentState = state; state = LOADING_MODULES; - modules.put(module.getId(), new ModuleContainer<>(module, cast(module.getDefaultConfiguration()))); - out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp)); + C configuration = module.getDefaultConfiguration(); + modules.put(module.getId(), new ModuleContainer<>(module, cast(configuration))); + out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp, configuration.getClass().getName())); state = currentState; module.onLoad(); lastActionTimestamp = currentTimeMillis(); @@ -204,8 +217,9 @@ public Context loadModule if (isNull(module)) throw new ContextInitializationException(MODULE_ID_IS_NULL); ContextState currentState = state; state = LOADING_MODULES; - modules.put(module.getId(), new ModuleContainer<>(module, cast(moduleConfigurator.configure(module)))); - out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp)); + C configuration = cast(moduleConfigurator.configure(module)); + modules.put(module.getId(), new ModuleContainer<>(module, configuration)); + out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp, configuration.getClass().getName())); state = currentState; module.onLoad(); lastActionTimestamp = currentTimeMillis(); @@ -216,10 +230,11 @@ public Context loadModule if (isNull(module)) throw new ContextInitializationException(MODULE_ID_IS_NULL); ContextState currentState = state; state = LOADING_MODULES; - modules.put(module.getId(), new ModuleContainer<>(module, cast(nonNull(customModuleConfiguration) ? customModuleConfiguration : module.getDefaultConfiguration()))); + C configuration = cast(nonNull(customModuleConfiguration) ? customModuleConfiguration : module.getDefaultConfiguration()); + modules.put(module.getId(), new ModuleContainer<>(module, configuration)); state = currentState; module.onLoad(); - out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp)); + out.println(format(MODULE_LOADED_MESSAGE, module.getId(), currentTimeMillis() - lastActionTimestamp, configuration.getClass().getName())); lastActionTimestamp = currentTimeMillis(); return this; } diff --git a/application-test/src/test/groovy/ru/art/test/specification/configuration/ConfigurationSpecification.groovy b/application-test/src/test/groovy/ru/art/test/specification/configuration/ConfigurationSpecification.groovy index 69012c2b5..53136d30e 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/configuration/ConfigurationSpecification.groovy +++ b/application-test/src/test/groovy/ru/art/test/specification/configuration/ConfigurationSpecification.groovy @@ -19,6 +19,7 @@ package ru.art.test.specification.configuration import org.apache.logging.log4j.Level import org.junit.Ignore import ru.art.config.module.ConfigModule +import ru.art.core.configurator.ModuleConfigurator import ru.art.http.constants.MimeToContentTypeMapper import ru.art.http.server.module.HttpServerModule import ru.art.logging.LoggingModule @@ -72,10 +73,10 @@ class ConfigurationSpecification extends Specification { writeModuleConfig(type) def configuration = new ConfigModuleConfiguration(configType: type) context().with { - loadModule new ConfigModule(), configuration + loadModule new ConfigModule(), { configuration } as ModuleConfigurator (configModule() as ConfigModuleConfiguration).configType = type - loadModule new LoggingModule(), lazyLoggingAgileConfiguration() - loadModule new HttpServerModule(), lazyHttpServerAgileConfiguration() + loadModule new LoggingModule(), { lazyLoggingAgileConfiguration() } as ModuleConfigurator + loadModule new HttpServerModule(), { lazyHttpServerAgileConfiguration() } as ModuleConfigurator refreshModule LOGGING_MODULE_ID refreshModule HTTP_SERVER_MODULE_ID } diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/ModulesLoadingSpecification.groovy b/application-test/src/test/groovy/ru/art/test/specification/core/ModulesLoadingSpecification.groovy new file mode 100644 index 000000000..eccc4b1c5 --- /dev/null +++ b/application-test/src/test/groovy/ru/art/test/specification/core/ModulesLoadingSpecification.groovy @@ -0,0 +1,100 @@ +package ru.art.test.specification.core + +import ru.art.core.configuration.ContextInitialConfiguration +import ru.art.core.configurator.ModuleConfigurator +import ru.art.core.module.ModuleConfiguration +import ru.art.core.provider.PreconfiguredModuleProvider +import spock.lang.Specification + +import java.lang.reflect.Field +import java.util.concurrent.atomic.AtomicReference + +import static java.lang.reflect.Modifier.FINAL +import static java.util.Optional.empty +import static java.util.Optional.of +import static ru.art.core.constants.ContextConstants.DEFAULT_MAIN_MODULE_ID +import static ru.art.core.context.Context.initContext +import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.* +import static ru.art.test.specification.core.TestModule.testModule +import static ru.art.test.specification.core.TestModule.testModuleState + +class ModulesLoadingSpecification extends Specification { + static applicationContextConfiguration = new ContextInitialConfiguration.ApplicationContextConfiguration(DEFAULT_MAIN_MODULE_ID, new PreconfiguredModuleProvider() { + @Override + Optional getModuleConfiguration(String moduleId) { + switch (moduleId) { + case TestModule.class.name: return of(new TestModuleFileConfiguration()) + default: empty() + } + } + }) + + def "should load modules default configuration"() { + when: + def value = testModule().value + + then: + value == DEFAULT + } + + def "should load modules file configuration"() { + setup: + initContext(applicationContextConfiguration) + + when: + def value = testModule().value + + then: + value == FROM_FILE + } + + def "should load modules override configuration"() { + setup: + initContext(applicationContextConfiguration).loadModule(new TestModule(), new TestModuleOverrideConfiguration()) + + when: + def value = testModule().value + + then: + value == OVERRIDE + } + + def "should save module between context changes"() { + setup: + testModuleState().add(DEFAULT) + + when: + initContext(applicationContextConfiguration).loadModule(new TestModule(), new TestModuleOverrideConfiguration()) + testModuleState().add(FROM_FILE) + + then: + testModuleState().collection == [DEFAULT, FROM_FILE] + } + + def "should load module configuration with accessing state and default configuration during real configuration creating"() { + setup: + testModuleState().add(DEFAULT) + + when: + initContext(applicationContextConfiguration).loadModule(new TestModule(), { new TestModuleAccessingDefaultsConfiguration() } as ModuleConfigurator) + + then: + testModule().value == DEFAULT + DEFAULT + testModuleState().collection == [DEFAULT, OVERRIDE] + } + + def cleanup() { + Field modifiersField = Field.class.getDeclaredFields0(false).find { field -> field.name == "modifiers" } + modifiersField.setAccessible(true) + + Field testModule = TestModule.class.getDeclaredField("testModule"); + modifiersField.setInt(testModule, testModule.getModifiers() & ~FINAL); + testModule.setAccessible(true) + testModule.set(null, new AtomicReference()) + + Field testModuleState = TestModule.class.getDeclaredField("testModuleState"); + modifiersField.setInt(testModuleState, testModuleState.getModifiers() & ~FINAL); + testModuleState.setAccessible(true) + testModuleState.set(null, new AtomicReference()); + } +} diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java new file mode 100644 index 000000000..7f0bf9448 --- /dev/null +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java @@ -0,0 +1,64 @@ +package ru.art.test.specification.core; + +import lombok.*; +import ru.art.core.module.Module; +import ru.art.core.module.*; +import ru.art.logging.*; +import static lombok.AccessLevel.*; +import static ru.art.config.extensions.ConfigExtensions.*; +import static ru.art.core.context.Context.*; +import static ru.art.core.factory.CollectionsFactory.*; +import static ru.art.logging.LoggingModule.*; +import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.*; +import java.util.*; + +@Getter +public class TestModule implements Module { + @Getter(lazy = true, value = PRIVATE) + private final static TestModuleConfiguration testModule = context().getModule(TestModule.class.getName(), TestModule::new); + @Getter(lazy = true, value = PRIVATE) + private final static TestModuleState testModuleState = context().getModuleState(TestModule.class.getName(), TestModule::new); + private final String id = TestModule.class.getName(); + private final TestModuleConfiguration defaultConfiguration = new TestModuleDefaultConfiguration(); + private final TestModuleState state = new TestModuleState(); + + public static TestModuleConfiguration testModule() { + if (contextIsNotReady()) { + loggingModule().getLogger(TestModule.class).info("Context is not ready. Using default configuration"); + return new TestModuleDefaultConfiguration(); + } + return getTestModule(); + } + + public static TestModuleState testModuleState() { + return getTestModuleState(); + } + + + interface TestModuleConfiguration extends ModuleConfiguration { + String FROM_FILE = "from file"; + String DEFAULT = "default"; + String OVERRIDE = "override"; + + String getValue(); + + @Getter + class TestModuleFileConfiguration implements TestModuleConfiguration { + private String value = configString("test", "value"); + } + + @Getter + class TestModuleDefaultConfiguration implements TestModuleConfiguration { + private String value = DEFAULT; + } + } + + @Getter + public static class TestModuleState implements ModuleState { + List collection = dynamicArrayOf(); + + void add(String element) { + collection.add(element); + } + } +} \ No newline at end of file diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleAccessingDefaultsConfiguration.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleAccessingDefaultsConfiguration.java new file mode 100644 index 000000000..54d7c579c --- /dev/null +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleAccessingDefaultsConfiguration.java @@ -0,0 +1,15 @@ +package ru.art.test.specification.core; + +import lombok.*; +import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.*; +import static ru.art.test.specification.core.TestModule.*; + +@Getter +public class TestModuleAccessingDefaultsConfiguration extends TestModuleFileConfiguration { + private final String value; + + public TestModuleAccessingDefaultsConfiguration() { + this.value = testModule().getValue() + testModuleState().collection.get(0); + testModuleState().add(OVERRIDE); + } +} \ No newline at end of file diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleOverrideConfiguration.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleOverrideConfiguration.java new file mode 100644 index 000000000..e4eaf06ce --- /dev/null +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleOverrideConfiguration.java @@ -0,0 +1,9 @@ +package ru.art.test.specification.core; + +import lombok.*; +import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.*; + +@Getter +public class TestModuleOverrideConfiguration extends TestModuleFileConfiguration { + private String value = OVERRIDE; +} \ No newline at end of file diff --git a/application-test/src/test/groovy/ru/art/test/specification/rsocket/RsocketSpecification.groovy b/application-test/src/test/groovy/ru/art/test/specification/rsocket/RsocketSpecification.groovy index 2346a687b..9686f513f 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/rsocket/RsocketSpecification.groovy +++ b/application-test/src/test/groovy/ru/art/test/specification/rsocket/RsocketSpecification.groovy @@ -20,6 +20,7 @@ package ru.art.test.specification.rsocket import reactor.core.publisher.Flux import ru.art.core.caster.Caster +import ru.art.core.configurator.ModuleConfigurator import ru.art.entity.Entity import ru.art.reactive.service.configuration.ReactiveServiceModuleConfiguration import ru.art.reactive.service.module.ReactiveServiceModule @@ -53,12 +54,18 @@ class RsocketSpecification extends Specification { static errorCode = MyException.class.name def setupSpec() { - useAgileConfigurations().loadModule(new ReactiveServiceModule(), new ReactiveServiceModuleConfiguration.ReactiveServiceModuleDefaultConfiguration() { - @Override - ReactiveServiceExceptionWrappers getReactiveServiceExceptionWrappers() { - return super.getReactiveServiceExceptionWrappers().add(MyException) { command, exception -> new ServiceExecutionException(command, errorCode, exception) } + def configurator = { + new ReactiveServiceModuleConfiguration.ReactiveServiceModuleDefaultConfiguration() { + @Override + ReactiveServiceExceptionWrappers getReactiveServiceExceptionWrappers() { + return super.getReactiveServiceExceptionWrappers().add(MyException) { command, exception -> + new ServiceExecutionException(command, errorCode, exception) + } + } } - }) + } as ModuleConfigurator + + useAgileConfigurations().loadModule(new ReactiveServiceModule(), configurator) } @Unroll diff --git a/application-test/src/test/resources/module-config.yml b/application-test/src/test/resources/module-config.yml index d3b3e05d0..a4efe4d2f 100644 --- a/application-test/src/test/resources/module-config.yml +++ b/application-test/src/test/resources/module-config.yml @@ -1,3 +1,5 @@ +test: + value: "from file" kafka: broker: port: 19092 From dd6366d7f99731d6593bda73b83dc7d77500c8db Mon Sep 17 00:00:00 2001 From: anton Date: Wed, 25 Mar 2020 03:27:21 +0300 Subject: [PATCH 3/6] refactoring to code style --- .../http/client/module/HttpClientModule.java | 28 ++++++++----------- .../test/specification/core/TestModule.java | 4 +-- 2 files changed, 14 insertions(+), 18 deletions(-) diff --git a/application-http-client/src/main/java/ru/art/http/client/module/HttpClientModule.java b/application-http-client/src/main/java/ru/art/http/client/module/HttpClientModule.java index 0418dd063..08bad425c 100644 --- a/application-http-client/src/main/java/ru/art/http/client/module/HttpClientModule.java +++ b/application-http-client/src/main/java/ru/art/http/client/module/HttpClientModule.java @@ -18,23 +18,19 @@ package ru.art.http.client.module; -import lombok.Getter; -import org.apache.http.client.methods.Configurable; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.logging.log4j.Logger; +import lombok.*; +import org.apache.http.impl.client.*; +import org.apache.http.impl.nio.client.*; +import org.apache.logging.log4j.*; import ru.art.core.module.Module; -import ru.art.http.client.configuration.HttpClientModuleConfiguration; -import ru.art.http.client.state.HttpClientModuleState; -import static java.text.MessageFormat.format; -import static lombok.AccessLevel.PRIVATE; -import static ru.art.core.context.Context.context; -import static ru.art.core.context.Context.contextIsNotReady; -import static ru.art.core.wrapper.ExceptionWrapper.ignoreException; -import static ru.art.http.client.configuration.HttpClientModuleConfiguration.DEFAULT_CONFIGURATION; -import static ru.art.http.client.constants.HttpClientModuleConstants.HTTP_CLIENT_CLOSING; -import static ru.art.http.client.constants.HttpClientModuleConstants.HTTP_CLIENT_MODULE_ID; -import static ru.art.logging.LoggingModule.loggingModule; +import ru.art.http.client.configuration.*; +import ru.art.http.client.state.*; +import static lombok.AccessLevel.*; +import static ru.art.core.context.Context.*; +import static ru.art.core.wrapper.ExceptionWrapper.*; +import static ru.art.http.client.configuration.HttpClientModuleConfiguration.*; +import static ru.art.http.client.constants.HttpClientModuleConstants.*; +import static ru.art.logging.LoggingModule.*; @Getter public class HttpClientModule implements Module { diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java index 7f0bf9448..a1aef3a9b 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java @@ -55,9 +55,9 @@ class TestModuleDefaultConfiguration implements TestModuleConfiguration { @Getter public static class TestModuleState implements ModuleState { - List collection = dynamicArrayOf(); + public List collection = dynamicArrayOf(); - void add(String element) { + public void add(String element) { collection.add(element); } } From e0dfb8f8c45df3c717bb94a71fb72c60e0729520 Mon Sep 17 00:00:00 2001 From: anton Date: Wed, 25 Mar 2020 03:27:58 +0300 Subject: [PATCH 4/6] refactoring to code style --- .../test/groovy/ru/art/test/specification/core/TestModule.java | 1 - 1 file changed, 1 deletion(-) diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java index a1aef3a9b..2fe98090b 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java @@ -3,7 +3,6 @@ import lombok.*; import ru.art.core.module.Module; import ru.art.core.module.*; -import ru.art.logging.*; import static lombok.AccessLevel.*; import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.core.context.Context.*; From 6e91cd828cacb183b28bf162ee2030d87188540c Mon Sep 17 00:00:00 2001 From: anton Date: Wed, 25 Mar 2020 03:43:27 +0300 Subject: [PATCH 5/6] refactoring to code style --- .../test/groovy/ru/art/test/specification/core/TestModule.java | 1 + 1 file changed, 1 insertion(+) diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java index 2fe98090b..a25bf27d2 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java @@ -11,6 +11,7 @@ import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.*; import java.util.*; + @Getter public class TestModule implements Module { @Getter(lazy = true, value = PRIVATE) From 25a781e09fcc267cb3045bfb595a4d4cdedc86b3 Mon Sep 17 00:00:00 2001 From: anton Date: Wed, 25 Mar 2020 04:03:28 +0300 Subject: [PATCH 6/6] fix --- application-test/build.gradle.kts | 7 ++++ .../core/ModulesLoadingSpecification.groovy | 2 +- .../test/specification/core/TestModule.java | 35 +------------------ ...tModuleAccessingDefaultsConfiguration.java | 2 +- .../core/TestModuleConfiguration.java | 11 ++++++ .../core/TestModuleDefaultConfiguration.java | 8 +++++ .../core/TestModuleFileConfiguration.java | 9 +++++ .../core/TestModuleOverrideConfiguration.java | 1 - .../specification/core/TestModuleState.java | 15 ++++++++ 9 files changed, 53 insertions(+), 37 deletions(-) create mode 100644 application-test/src/test/groovy/ru/art/test/specification/core/TestModuleConfiguration.java create mode 100644 application-test/src/test/groovy/ru/art/test/specification/core/TestModuleDefaultConfiguration.java create mode 100644 application-test/src/test/groovy/ru/art/test/specification/core/TestModuleFileConfiguration.java create mode 100644 application-test/src/test/groovy/ru/art/test/specification/core/TestModuleState.java diff --git a/application-test/build.gradle.kts b/application-test/build.gradle.kts index 6050241b9..20c631d7d 100644 --- a/application-test/build.gradle.kts +++ b/application-test/build.gradle.kts @@ -1,3 +1,5 @@ +import ru.art.gradle.constants.lombok + /* * ART Java * @@ -28,4 +30,9 @@ configurations { with(testRuntimeClasspath.get()) { exclude("org.apache.logging.log4j") } +} + +dependencies { + annotationProcessor(lombok().inGradleNotation()) + testAnnotationProcessor(lombok().inGradleNotation()) } \ No newline at end of file diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/ModulesLoadingSpecification.groovy b/application-test/src/test/groovy/ru/art/test/specification/core/ModulesLoadingSpecification.groovy index eccc4b1c5..7f03f9d5d 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/core/ModulesLoadingSpecification.groovy +++ b/application-test/src/test/groovy/ru/art/test/specification/core/ModulesLoadingSpecification.groovy @@ -14,9 +14,9 @@ import static java.util.Optional.empty import static java.util.Optional.of import static ru.art.core.constants.ContextConstants.DEFAULT_MAIN_MODULE_ID import static ru.art.core.context.Context.initContext -import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.* import static ru.art.test.specification.core.TestModule.testModule import static ru.art.test.specification.core.TestModule.testModuleState +import static ru.art.test.specification.core.TestModuleConfiguration.* class ModulesLoadingSpecification extends Specification { static applicationContextConfiguration = new ContextInitialConfiguration.ApplicationContextConfiguration(DEFAULT_MAIN_MODULE_ID, new PreconfiguredModuleProvider() { diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java index a25bf27d2..e549792cd 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModule.java @@ -2,18 +2,13 @@ import lombok.*; import ru.art.core.module.Module; -import ru.art.core.module.*; import static lombok.AccessLevel.*; -import static ru.art.config.extensions.ConfigExtensions.*; import static ru.art.core.context.Context.*; -import static ru.art.core.factory.CollectionsFactory.*; import static ru.art.logging.LoggingModule.*; -import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.*; -import java.util.*; @Getter -public class TestModule implements Module { +public class TestModule implements Module { @Getter(lazy = true, value = PRIVATE) private final static TestModuleConfiguration testModule = context().getModule(TestModule.class.getName(), TestModule::new); @Getter(lazy = true, value = PRIVATE) @@ -33,32 +28,4 @@ public static TestModuleConfiguration testModule() { public static TestModuleState testModuleState() { return getTestModuleState(); } - - - interface TestModuleConfiguration extends ModuleConfiguration { - String FROM_FILE = "from file"; - String DEFAULT = "default"; - String OVERRIDE = "override"; - - String getValue(); - - @Getter - class TestModuleFileConfiguration implements TestModuleConfiguration { - private String value = configString("test", "value"); - } - - @Getter - class TestModuleDefaultConfiguration implements TestModuleConfiguration { - private String value = DEFAULT; - } - } - - @Getter - public static class TestModuleState implements ModuleState { - public List collection = dynamicArrayOf(); - - public void add(String element) { - collection.add(element); - } - } } \ No newline at end of file diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleAccessingDefaultsConfiguration.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleAccessingDefaultsConfiguration.java index 54d7c579c..6df9c77e4 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleAccessingDefaultsConfiguration.java +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleAccessingDefaultsConfiguration.java @@ -1,7 +1,7 @@ package ru.art.test.specification.core; import lombok.*; -import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.*; +import ru.art.test.specification.core.TestModuleConfiguration.*; import static ru.art.test.specification.core.TestModule.*; @Getter diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleConfiguration.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleConfiguration.java new file mode 100644 index 000000000..61a263e1f --- /dev/null +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleConfiguration.java @@ -0,0 +1,11 @@ +package ru.art.test.specification.core; + +import ru.art.core.module.*; + +public interface TestModuleConfiguration extends ModuleConfiguration { + String FROM_FILE = "from file"; + String DEFAULT = "default"; + String OVERRIDE = "override"; + + String getValue(); +} \ No newline at end of file diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleDefaultConfiguration.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleDefaultConfiguration.java new file mode 100644 index 000000000..a3af49094 --- /dev/null +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleDefaultConfiguration.java @@ -0,0 +1,8 @@ +package ru.art.test.specification.core; + +import lombok.*; + +@Getter +public class TestModuleDefaultConfiguration implements TestModuleConfiguration { + private String value = DEFAULT; +} \ No newline at end of file diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleFileConfiguration.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleFileConfiguration.java new file mode 100644 index 000000000..92bd1af81 --- /dev/null +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleFileConfiguration.java @@ -0,0 +1,9 @@ +package ru.art.test.specification.core; + +import lombok.*; +import static ru.art.config.extensions.ConfigExtensions.configString; + +@Getter +public class TestModuleFileConfiguration implements TestModuleConfiguration { + private String value = configString("test", "value"); +} \ No newline at end of file diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleOverrideConfiguration.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleOverrideConfiguration.java index e4eaf06ce..05c12c813 100644 --- a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleOverrideConfiguration.java +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleOverrideConfiguration.java @@ -1,7 +1,6 @@ package ru.art.test.specification.core; import lombok.*; -import static ru.art.test.specification.core.TestModule.TestModuleConfiguration.*; @Getter public class TestModuleOverrideConfiguration extends TestModuleFileConfiguration { diff --git a/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleState.java b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleState.java new file mode 100644 index 000000000..4ea1440a0 --- /dev/null +++ b/application-test/src/test/groovy/ru/art/test/specification/core/TestModuleState.java @@ -0,0 +1,15 @@ +package ru.art.test.specification.core; + +import lombok.*; +import ru.art.core.module.*; +import static ru.art.core.factory.CollectionsFactory.*; +import java.util.*; + +@Getter +public class TestModuleState implements ModuleState { + public List collection = dynamicArrayOf(); + + public void add(String element) { + collection.add(element); + } +} \ No newline at end of file